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 rereading the whole reply on every streamed arrival (#9012)

Daniel Han564035f1c664
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 6ded83325fd..ce89d20d7f8 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -163,10 +163,11 @@ import {
import { createRetryableSharedRead } from "../utils/retryable-shared-read";
import { getImageInputUnavailableReason } from "../utils/image-input-support";
import {
+ createThinkTagTracker,
extractDeltaText,
- hasUnclosedThinkTag,
parseAssistantContent,
} from "../utils/parse-assistant-content";
+import { stripTrailingTemplatePlaceholder } from "../utils/trailing-template-placeholder";
import { createStreamPublishGate } from "../utils/stream-pacing";
import {
countReasoningGroups,
@@ -4669,6 +4670,11 @@ export function createOpenAIStreamAdapter(
// Seeded with the partial so the bubble reads as one response; the boundary lets
// the finalizers re-derive the new output and repair a repeat/restart.
let cumulativeText = continuation ? continuation.partial : "";
+ // Answers "does the text end inside <think>" from what each arrival adds
+ // rather than from the whole buffer. It has to see every state the buffer
+ // passes through, so it is updated once per arrival, next to the strip
+ // below, and never behind a short-circuiting condition.
+ const thinkTags = createThinkTagTracker();
// What the cap is measured against: only grows, unlike cumulativeText,
// and counts tool-argument deltas, which never reach it.
let streamedChars = 0;
@@ -6328,11 +6334,14 @@ export function createOpenAIStreamAdapter(
// Strip a trailing ${...} template-literal fragment from
// external streams (mistral magistral occasionally emits one).
if (isExternalRequest) {
- cumulativeText = cumulativeText.replace(
- /\s*\$\{[^}]*\}\s*$/,
- "",
- );
+ cumulativeText =
+ stripTrailingTemplatePlaceholder(cumulativeText);
}
+ // Right after the strip, so the tracker sees the buffer the
+ // arrival ended with. Kept out of the short-circuiting condition
+ // below: skipping arrivals would leave the strip's removals
+ // unaccounted for.
+ const textEndsInsideThink = thinkTags.update(cumulativeText);
const assistantContent = liveAssistantContent();
// Fallback when no server-side reasoning_summary arrives.
@@ -6360,7 +6369,7 @@ export function createOpenAIStreamAdapter(
reasoningDurationTracker.hasActiveGroup &&
!reasoningContentOpen &&
!structuredReasoningContinues &&
- !hasUnclosedThinkTag(cumulativeText)
+ !textEndsInsideThink
) {
reasoningDurationTracker.finishGroup();
}
diff --git a/studio/frontend/src/features/chat/utils/parse-assistant-content.ts b/studio/frontend/src/features/chat/utils/parse-assistant-content.ts
index dd987d6701d..40d0d14d248 100644
--- a/studio/frontend/src/features/chat/utils/parse-assistant-content.ts
+++ b/studio/frontend/src/features/chat/utils/parse-assistant-content.ts
@@ -80,9 +80,8 @@ export function extractDeltaText(delta: unknown): {
return { text, structuredReasoningContinues };
}
-// ContentPart from @assistant-ui/react has readonly fields, so coalescing via
-// `last.text += text` fails (TS2540). Instead replace the last element with a
-// fresh merged object: same allocation cost as mutation but type-safe.
+// ContentPart from @assistant-ui/react has readonly fields, so `last.text +=
+// text` fails (TS2540). Replace the last element with a merged object instead.
function appendTextPart(parts: ContentPart[], text: string): void {
if (!text) return;
@@ -139,3 +138,73 @@ export function parseAssistantContent(
export function hasUnclosedThinkTag(raw: string): boolean {
return raw.lastIndexOf(THINK_OPEN_TAG) > raw.lastIndexOf(THINK_CLOSE_TAG);
}
+
+/**
+ * The most characters of a `<think>` or `</think>` that can sit before the point
+ * a previous call stopped at: one short of the longer tag, since a tag
+ * straddling the boundary has at least one character on the new side.
+ */
+const THINK_TAG_OVERLAP =
+ Math.max(THINK_OPEN_TAG.length, THINK_CLOSE_TAG.length) - 1;
+
+export type ThinkTagTracker = {
+ /**
+ * Whether `text` ends inside a `<think>` block, that is, what
+ * `hasUnclosedThinkTag(text)` returns.
+ *
+ * `text` must be the previous call's text with characters appended and then,
+ * at most once, a suffix removed. That is the only way the streaming adapter's
+ * buffer changes: deltas are appended, and the trailing template-literal strip
+ * takes a suffix off the end. An unrelated string, or one whose committed
+ * prefix was rewritten, gets an answer based on stale tag positions.
+ */
+ update(text: string): boolean;
+};
+
+/**
+ * Track `hasUnclosedThinkTag` across a stream without rereading the buffer.
+ *
+ * `hasUnclosedThinkTag` walks the whole reply, so calling it once per SSE
+ * arrival costs O(reply^2) over a reply. This keeps the index of the last open
+ * and close tag and looks only at what arrived since the previous call, plus the
+ * few characters in front of it that a tag split across arrivals can occupy. A
+ * `<think>` delivered one character at a time over seven arrivals is found on
+ * the arrival that completes it.
+ */
+export function createThinkTagTracker(): ThinkTagTracker {
+ // Everything before this offset has been scanned; the indices are the last
+ // position of each tag in it, or -1, exactly as `lastIndexOf` reports.
+ let scanned = 0;
+ let lastOpen = -1;
+ let lastClose = -1;
+
+ return {
+ update(text: string): boolean {
+ if (text.length >= scanned) {
+ const from = Math.max(0, scanned - THINK_TAG_OVERLAP);
+ const arrived = text.slice(from);
+ // A tag re-found inside the overlap is one already recorded, so it can
+ // only reproduce the index it gave last time.
+ const openAt = arrived.lastIndexOf(THINK_OPEN_TAG);
+ if (openAt !== -1) {
+ lastOpen = Math.max(lastOpen, from + openAt);
+ }
+ const closeAt = arrived.lastIndexOf(THINK_CLOSE_TAG);
+ if (closeAt !== -1) {
+ lastClose = Math.max(lastClose, from + closeAt);
+ }
+ } else {
+ // A suffix went away. Re-find only the tags that left with it; the
+ // ordinary case, a strip of plain text, costs nothing here.
+ if (lastOpen >= 0 && lastOpen + THINK_OPEN_TAG.length > text.length) {
+ lastOpen = text.lastIndexOf(THINK_OPEN_TAG);
+ }
+ if (lastClose >= 0 && lastClose + THINK_CLOSE_TAG.length > text.length) {
+ lastClose = text.lastIndexOf(THINK_CLOSE_TAG);
+ }
+ }
+ scanned = text.length;
+ return lastOpen > lastClose;
+ },
+ };
+}
diff --git a/studio/frontend/src/features/chat/utils/trailing-template-placeholder.ts b/studio/frontend/src/features/chat/utils/trailing-template-placeholder.ts
new file mode 100644
index 00000000000..552d960cce3
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/trailing-template-placeholder.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Some external providers (mistral magistral, occasionally) leak a trailing
+ * template-literal fragment such as `${answer}` into the stream, so the adapter
+ * strips one off the end of the accumulated reply on every arrival.
+ *
+ * The pattern below is anchored at the end, but a regex engine still tries it at
+ * every start offset, so running it over the whole buffer costs O(reply) per
+ * arrival and O(reply^2) over a reply. This module runs the same pattern over a
+ * bounded suffix instead.
+ */
+
+/**
+ * How far back the opening `${` may sit. Providers emit short placeholders, so
+ * an opener further back than this is not treated as one.
+ *
+ * The guarantee is about what is REMOVED, not about what is left whole: this
+ * removes no more than the unbounded pattern would, and always returns a prefix
+ * of the input, so it can never delete text the unbounded pattern kept. Asserted
+ * across windows of 1, 2, 4, 8 and 16 characters.
+ *
+ * "The oversized fragment is left whole" is the usual consequence, not the rule.
+ * Nested placeholders show the difference: in
+ * `"answer ${" + "a".repeat(4196) + "${nested}"` the outer opener is out of
+ * window, so the inner `${nested}` is stripped and the outer text stays. The
+ * unbounded pattern deletes 4,208 characters here; this deletes 9. Less is
+ * removed, the direction that matters, but the outer fragment is not untouched.
+ */
+export const TRAILING_PLACEHOLDER_WINDOW = 4096;
+
+const TRAILING_TEMPLATE_PLACEHOLDER = /\s*\$\{[^}]*\}\s*$/;
+const WHITESPACE = /\s/;
+const CLOSE_BRACE = "}";
+
+/**
+ * Remove one trailing `${...}` fragment, with the whitespace around it.
+ *
+ * Equivalent to `text.replace(/\s*\$\{[^}]*\}\s*$/, "")` for fragments up to
+ * `window` characters long, at a cost independent of the reply preceding it.
+ */
+export function stripTrailingTemplatePlaceholder(
+ text: string,
+ window: number = TRAILING_PLACEHOLDER_WINDOW,
+): string {
+ // `\s*$` can only match the whitespace run at the very end, and the character
+ // in front of it has to be the closing brace. Almost every arrival fails here
+ // for the cost of that run, which is where the quadratic term goes. The run is
+ // walked no further than the window, so a reply ending in a growing field of
+ // whitespace cannot reintroduce it.
+ const floor = Math.max(0, text.length - window);
+ let end = text.length;
+ while (end > floor && WHITESPACE.test(text[end - 1])) {
+ end -= 1;
+ }
+ if (end === 0 || text[end - 1] !== CLOSE_BRACE) {
+ return text;
+ }
+
+ // `[^}]*` cannot span a `}`, so the opening `${` has to sit after the previous
+ // `}`. The window keeps the search off the whole buffer; the previous `}` then
+ // usually keeps it far shorter still, since brace-heavy replies are the ones
+ // that reach here.
+ const from = Math.max(0, end - 1 - window);
+ const tail = text.slice(from);
+ const previousBrace = tail.lastIndexOf(CLOSE_BRACE, end - 2 - from);
+ const scanFrom = previousBrace === -1 ? 0 : previousBrace + 1;
+ const match = TRAILING_TEMPLATE_PLACEHOLDER.exec(tail.slice(scanFrom));
+ if (!match) {
+ return text;
+ }
+ return text.slice(0, from + scanFrom + match.index);
+}
diff --git a/studio/frontend/tests/chat-adapter-scan-cost.test.ts b/studio/frontend/tests/chat-adapter-scan-cost.test.ts
new file mode 100644
index 00000000000..122bbe3eaa4
--- /dev/null
+++ b/studio/frontend/tests/chat-adapter-scan-cost.test.ts
@@ -0,0 +1,325 @@
+// 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 { readFileSync } from "node:fs";
+import test from "node:test";
+
+import {
+ createThinkTagTracker,
+ hasUnclosedThinkTag,
+} from "../src/features/chat/utils/parse-assistant-content.ts";
+import { stripTrailingTemplatePlaceholder } from "../src/features/chat/utils/trailing-template-placeholder.ts";
+
+/**
+ * Complexity tests, not timing tests: they count the characters the scans look
+ * at, so they say the same thing on an idle laptop and a loaded CI box. Every
+ * string primitive the scans use is counted by what it can read:
+ *
+ * String replace / lastIndexOf / indexOf the receiver's length
+ * String slice the length it produces
+ * RegExp exec / test the length of the subject
+ *
+ * `test` is included because the bounded strip walks the trailing whitespace run
+ * one character at a time; each read shows up as a one-character subject, so a
+ * runaway walk is counted rather than hidden.
+ */
+type Counted = { chars: number };
+
+function withScanAccounting<T>(body: () => T): { result: T; chars: number } {
+ const counted: Counted = { chars: 0 };
+ const realReplace = String.prototype.replace;
+ const realLastIndexOf = String.prototype.lastIndexOf;
+ const realIndexOf = String.prototype.indexOf;
+ const realSlice = String.prototype.slice;
+ const realExec = RegExp.prototype.exec;
+ const realTest = RegExp.prototype.test;
+
+ type Unknown = (...args: unknown[]) => unknown;
+ const countReceiver = (real: Unknown): Unknown =>
+ function counting(this: string, ...args: unknown[]) {
+ counted.chars += this.length;
+ return real.apply(this, args);
+ };
+
+ String.prototype.replace = countReceiver(
+ realReplace as unknown as Unknown,
+ ) as unknown as typeof realReplace;
+ String.prototype.lastIndexOf = countReceiver(
+ realLastIndexOf as unknown as Unknown,
+ ) as unknown as typeof realLastIndexOf;
+ String.prototype.indexOf = countReceiver(
+ realIndexOf as unknown as Unknown,
+ ) as unknown as typeof realIndexOf;
+ String.prototype.slice = function countingSlice(
+ this: string,
+ start?: number,
+ end?: number,
+ ): string {
+ const out = realSlice.call(this, start, end);
+ counted.chars += out.length;
+ return out;
+ };
+ RegExp.prototype.exec = function countingExec(
+ this: RegExp,
+ subject: string,
+ ): RegExpExecArray | null {
+ counted.chars += String(subject).length;
+ return realExec.call(this, subject);
+ };
+ RegExp.prototype.test = function countingTest(
+ this: RegExp,
+ subject: string,
+ ): boolean {
+ counted.chars += String(subject).length;
+ return realTest.call(this, subject);
+ };
+
+ try {
+ const result = body();
+ return { result, chars: counted.chars };
+ } finally {
+ String.prototype.replace = realReplace;
+ String.prototype.lastIndexOf = realLastIndexOf;
+ String.prototype.indexOf = realIndexOf;
+ String.prototype.slice = realSlice;
+ RegExp.prototype.exec = realExec;
+ RegExp.prototype.test = realTest;
+ }
+}
+
+// --------------------------------------------------------------- fixture ---
+
+const WORDS = [
+ "the", "model", "streams", "an", "answer", "one", "token", "at", "a", "time",
+ "so", "the", "adapter", "sees", "the", "whole", "reply", "again", "on",
+ "every", "arrival", "which", "is", "what", "makes", "the", "tail", "of", "a",
+ "long", "reply", "slower", "than", "its", "head",
+];
+
+function prose(chars: number, seed: number): string {
+ let out = "";
+ let value = seed;
+ while (out.length < chars) {
+ value = (value * 1103515245 + 12345) & 0x7fffffff;
+ out += WORDS[value % WORDS.length];
+ out += (value & 31) === 0 ? ".\n\n" : " ";
+ }
+ return out.slice(0, chars);
+}
+
+function code(chars: number): string {
+ let out = "```ts\n";
+ let index = 0;
+ while (out.length < chars) {
+ out += `export function step${index}(input: Record<string, number>) {\n`;
+ out += ` return { ...input, n: ${index} };\n}\n\n`;
+ index += 1;
+ }
+ return `${out.slice(0, Math.max(7, chars - 4))}\n\`\`\`\n`;
+}
+
+/** A reply shaped like a reasoning model's: think block, prose, code. */
+function buildReply(chars: number): string {
+ const think = `<think>${prose(Math.round(chars * 0.25), 1)}</think>`;
+ const body = prose(Math.round(chars * 0.5), 2);
+ return `${think}\n\n${body}\n\n${code(Math.round(chars * 0.25))}`;
+}
+
+function arrivalsOf(text: string, size = 4): string[] {
+ const out: string[] = [];
+ for (let at = 0; at < text.length; at += size) {
+ out.push(text.slice(at, at + size));
+ }
+ return out;
+}
+
+// ------------------------------------------------------------- the scans ---
+
+/** What the adapter ran before: the whole buffer, on every arrival. */
+const UNBOUNDED = /\s*\$\{[^}]*\}\s*$/;
+
+function runStrip(
+ arrivals: string[],
+ strip: (text: string) => string,
+): number {
+ let text = "";
+ for (const chunk of arrivals) {
+ text += chunk;
+ text = strip(text);
+ }
+ return text.length;
+}
+
+function runThink(
+ arrivals: string[],
+ ask: (text: string) => boolean,
+): number {
+ let text = "";
+ let unclosed = 0;
+ for (const chunk of arrivals) {
+ text += chunk;
+ if (ask(text)) unclosed += 1;
+ }
+ return unclosed;
+}
+
+const SMALL = 16_000;
+const LARGE = 32_000;
+
+function stripCost(chars: number, strip: (text: string) => string): number {
+ const arrivals = arrivalsOf(buildReply(chars));
+ return withScanAccounting(() => runStrip(arrivals, strip)).chars;
+}
+
+function thinkCost(chars: number, ask: () => (text: string) => boolean): number {
+ const arrivals = arrivalsOf(buildReply(chars));
+ const asker = ask();
+ return withScanAccounting(() => runThink(arrivals, asker)).chars;
+}
+
+// ------------------------------------------------------------------ tests ---
+
+test("the trailing placeholder strip is linear in the reply length", () => {
+ const small = stripCost(SMALL, stripTrailingTemplatePlaceholder);
+ const large = stripCost(LARGE, stripTrailingTemplatePlaceholder);
+ const growth = large / small;
+
+ // Twice the reply, twice the arrivals, so a scan whose per-arrival cost is
+ // independent of what came before doubles. Near 4 means the whole buffer is
+ // being read again on every arrival.
+ assert.equal(
+ growth < 2.5,
+ true,
+ `strip cost grew ${growth.toFixed(2)}x for twice the reply (${small} -> ${large} chars scanned); that is not linear`,
+ );
+
+ // The defect it replaces, measured the same way, so the test states what it
+ // guards against rather than only asserting a number.
+ const unboundedSmall = stripCost(SMALL, (text) => text.replace(UNBOUNDED, ""));
+ const unboundedLarge = stripCost(LARGE, (text) => text.replace(UNBOUNDED, ""));
+ const unboundedGrowth = unboundedLarge / unboundedSmall;
+ assert.equal(
+ unboundedGrowth > 3.5,
+ true,
+ `the unbounded pattern grew ${unboundedGrowth.toFixed(2)}x, so this test is no longer measuring the difference it was written for`,
+ );
+ assert.equal(
+ large * 10 < unboundedLarge,
+ true,
+ `bounded strip scanned ${large} chars against ${unboundedLarge} for the unbounded pattern; expected at least 10x fewer`,
+ );
+});
+
+test("think tag tracking is linear in the reply length", () => {
+ const small = thinkCost(SMALL, () => {
+ const tracker = createThinkTagTracker();
+ return (text: string) => tracker.update(text);
+ });
+ const large = thinkCost(LARGE, () => {
+ const tracker = createThinkTagTracker();
+ return (text: string) => tracker.update(text);
+ });
+ const growth = large / small;
+ assert.equal(
+ growth < 2.5,
+ true,
+ `tracker cost grew ${growth.toFixed(2)}x for twice the reply (${small} -> ${large} chars scanned); that is not linear`,
+ );
+
+ // Each character is read a small fixed number of times, so the total is a
+ // multiple of the reply, not of the reply squared.
+ assert.equal(
+ large < LARGE * 30,
+ true,
+ `tracker scanned ${large} chars for a ${LARGE} character reply`,
+ );
+
+ const rescanSmall = thinkCost(SMALL, () => hasUnclosedThinkTag);
+ const rescanLarge = thinkCost(LARGE, () => hasUnclosedThinkTag);
+ const rescanGrowth = rescanLarge / rescanSmall;
+ assert.equal(
+ rescanGrowth > 3.5,
+ true,
+ `the full rescan grew ${rescanGrowth.toFixed(2)}x, so this test is no longer measuring the difference it was written for`,
+ );
+ assert.equal(
+ large * 10 < rescanLarge,
+ true,
+ `tracker scanned ${large} chars against ${rescanLarge} for the full rescan; expected at least 10x fewer`,
+ );
+});
+
+// ------------------------------------------------------------ source pins ---
+
+const ADAPTER = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+);
+
+/** Drop comments, so a commented-out call cannot satisfy a search. */
+function withoutComments(source: string): string {
+ return source
+ .replace(/\/\*[\s\S]*?\*\//g, "")
+ .split("\n")
+ .map((line) => {
+ const at = line.indexOf("//");
+ if (at === -1) {
+ return line;
+ }
+ // Keep a "//" inside a string literal, as in "https://".
+ const quotes = line.slice(0, at).match(/["'`]/g)?.length ?? 0;
+ return quotes % 2 === 1 ? line : line.slice(0, at);
+ })
+ .join("\n");
+}
+
+test("the adapter strips the trailing fragment through the bounded scan", () => {
+ const source = withoutComments(ADAPTER);
+ assert.match(source, /stripTrailingTemplatePlaceholder\(cumulativeText\)/);
+ assert.doesNotMatch(
+ source,
+ /cumulativeText\.replace\(/,
+ "the whole buffer is being rewritten again; use the bounded scan",
+ );
+ assert.doesNotMatch(
+ source,
+ /\\s\*\\\$\\\{\[\^}\]\*\\\}\\s\*\$/,
+ "the unbounded pattern is back in the adapter",
+ );
+});
+
+test("the adapter asks the tracker once per arrival, not inside a condition", () => {
+ const source = withoutComments(ADAPTER);
+ assert.doesNotMatch(
+ source,
+ /hasUnclosedThinkTag\(/,
+ "the whole buffer is being reread; use the tracker",
+ );
+
+ const updates = source.match(/thinkTags\.update\(/g) ?? [];
+ assert.equal(
+ updates.length,
+ 1,
+ "the tracker has to see every state the buffer passes through, so exactly one call site",
+ );
+
+ // The call has to be its own statement: inside the `&&` chain below, the
+ // short-circuit would skip arrivals, and a strip on a skipped arrival would
+ // leave the tracker's recorded tag positions describing text that is gone.
+ assert.match(
+ source,
+ /const textEndsInsideThink = thinkTags\.update\(cumulativeText\);/,
+ );
+ assert.match(source, /&&\s*!textEndsInsideThink\s*\)/);
+
+ const strip = source.indexOf("stripTrailingTemplatePlaceholder(cumulativeText)");
+ const update = source.indexOf("thinkTags.update(cumulativeText)");
+ const ask = source.indexOf("!textEndsInsideThink");
+ assert.equal(strip !== -1 && update !== -1 && ask !== -1, true);
+ assert.equal(
+ strip < update && update < ask,
+ true,
+ "the tracker must be updated after the strip and before the buffer is asked about",
+ );
+});
diff --git a/studio/frontend/tests/think-tag-tracker.test.ts b/studio/frontend/tests/think-tag-tracker.test.ts
new file mode 100644
index 00000000000..48cacc24044
--- /dev/null
+++ b/studio/frontend/tests/think-tag-tracker.test.ts
@@ -0,0 +1,274 @@
+// 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 {
+ createThinkTagTracker,
+ hasUnclosedThinkTag,
+} from "../src/features/chat/utils/parse-assistant-content.ts";
+
+/**
+ * Feed `chunks` in order and assert the tracker agrees with a full rescan after
+ * each one. `hasUnclosedThinkTag` is the reference: the tracker exists only to
+ * give the same answer without rereading the buffer.
+ */
+function assertAgreesOnStream(
+ chunks: string[],
+ label: string,
+): { unclosed: number; closed: number } {
+ const tracker = createThinkTagTracker();
+ let text = "";
+ let unclosed = 0;
+ let closed = 0;
+ for (const [index, chunk] of chunks.entries()) {
+ text += chunk;
+ const answer = hasUnclosedThinkTag(text);
+ assert.equal(
+ tracker.update(text),
+ answer,
+ `${label}: disagreed after chunk ${index} (${JSON.stringify(chunk)}), buffer ${JSON.stringify(text)}`,
+ );
+ if (answer) unclosed += 1;
+ else closed += 1;
+ }
+ return { unclosed, closed };
+}
+
+/** Every way of cutting `tag` into `parts` non-empty pieces. */
+function splits(tag: string, parts: number): string[][] {
+ if (parts === 1) return [[tag]];
+ const out: string[][] = [];
+ for (let cut = 1; cut <= tag.length - (parts - 1); cut += 1) {
+ for (const rest of splits(tag.slice(cut), parts - 1)) {
+ out.push([tag.slice(0, cut), ...rest]);
+ }
+ }
+ return out;
+}
+
+test("an opening tag split across two, three and four arrivals is seen", () => {
+ for (const parts of [2, 3, 4]) {
+ for (const pieces of splits("<think>", parts)) {
+ assertAgreesOnStream(
+ ["before ", ...pieces, "reasoning"],
+ `<think> in ${parts} parts as ${JSON.stringify(pieces)}`,
+ );
+ }
+ }
+});
+
+test("a closing tag split across two, three and four arrivals is seen", () => {
+ for (const parts of [2, 3, 4]) {
+ for (const pieces of splits("</think>", parts)) {
+ assertAgreesOnStream(
+ ["<think>reasoning", ...pieces, " answer"],
+ `</think> in ${parts} parts as ${JSON.stringify(pieces)}`,
+ );
+ }
+ }
+});
+
+test("tags delivered one character per arrival are seen", () => {
+ assertAgreesOnStream(
+ [..."prefix <think>thought</think> answer"],
+ "one character per arrival",
+ );
+});
+
+test("a tag split across arrivals that carry nothing else is seen", () => {
+ // Worst case for too short an overlap: one tag character per arrival, with
+ // empty arrivals in between.
+ assertAgreesOnStream(
+ ["a", "<", "", "t", "", "h", "i", "", "n", "k", "", ">", "b"],
+ "empty arrivals between tag characters",
+ );
+ assertAgreesOnStream(
+ ["<think>a", "<", "/", "t", "h", "i", "n", "k", ">", "b"],
+ "</think> one character at a time",
+ );
+});
+
+test("repeated reasoning blocks track the last tag, not the first", () => {
+ assertAgreesOnStream(
+ [
+ "<think>",
+ "one",
+ "</think>",
+ "answer ",
+ "<think>",
+ "two",
+ "</think>",
+ "more ",
+ "<think>",
+ "three",
+ ],
+ "three reasoning blocks",
+ );
+});
+
+test("a near miss is not mistaken for a tag", () => {
+ assertAgreesOnStream(
+ [..."<thin> <think > </thin> <thinks> <think>x</think >"],
+ "near misses",
+ );
+});
+
+test("a stream seeded with a continuation partial is tracked", () => {
+ const tracker = createThinkTagTracker();
+ let text = "<think>resumed reasoning";
+ assert.equal(tracker.update(text), hasUnclosedThinkTag(text));
+ text += "</think> answer";
+ assert.equal(tracker.update(text), hasUnclosedThinkTag(text));
+});
+
+test("a suffix removed from the buffer is accounted for", () => {
+ // The adapter strips a trailing ${...} fragment after appending, so its
+ // buffer can be shorter than the one from the arrival before.
+ const cases: Array<{ steps: string[]; label: string }> = [
+ { steps: ["<think>a", "<think>a ${x}", "<think>a"], label: "plain strip" },
+ {
+ steps: ["<think>a</think>", "<think>a</think> ${x}", "<think>a</think>"],
+ label: "strip after a close",
+ },
+ {
+ // The suffix takes the closing tag with it, so the buffer is unclosed
+ // again and the tracker has to find the earlier close.
+ steps: ["<think>a</think>b</think>", "<think>a</think>b"],
+ label: "strip removes the last close tag",
+ },
+ {
+ // The removed suffix takes the opening tag with it.
+ steps: ["<think>a</think>b<think>c", "<think>a</think>b"],
+ label: "strip removes the last open tag",
+ },
+ {
+ // Removed back past a tag that was never scanned on its own.
+ steps: ["a<think>b</think>c", "a"],
+ label: "strip removes both tags",
+ },
+ ];
+ for (const { steps, label } of cases) {
+ const tracker = createThinkTagTracker();
+ for (const [index, text] of steps.entries()) {
+ assert.equal(
+ tracker.update(text),
+ hasUnclosedThinkTag(text),
+ `${label}: disagreed at step ${index} on ${JSON.stringify(text)}`,
+ );
+ }
+ }
+});
+
+test("append then strip within one arrival is tracked", () => {
+ // What the adapter does: append the delta, strip a trailing fragment, then
+ // ask once. Only the post-strip buffer is ever seen.
+ const tracker = createThinkTagTracker();
+ const deltas = [
+ "<think>",
+ "reasoning ",
+ "</think>",
+ " answer ${x}",
+ " continues",
+ "<think>more ${y}",
+ "</think>",
+ ];
+ const strip = (text: string): string => text.replace(/\s*\$\{[^}]*\}\s*$/, "");
+ let text = "";
+ for (const [index, delta] of deltas.entries()) {
+ text = strip(text + delta);
+ assert.equal(
+ tracker.update(text),
+ hasUnclosedThinkTag(text),
+ `disagreed after delta ${index} on ${JSON.stringify(text)}`,
+ );
+ }
+});
+
+/**
+ * Deterministic pseudo-random generator. A plain `seed * 1103515245` loop is not
+ * usable here: the product runs past 2^53, so the sampled low bits come out
+ * constant and half of any alphabet is never drawn.
+ */
+function mulberry32(seed: number): () => number {
+ let state = seed >>> 0;
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let t = state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return (t ^ (t >>> 14)) >>> 0;
+ };
+}
+
+test("tracker agrees with a full rescan on random streams", () => {
+ const alphabet = [
+ "<",
+ ">",
+ "/",
+ "t",
+ "h",
+ "i",
+ "n",
+ "k",
+ "<think>",
+ "</think>",
+ "x",
+ " ",
+ "<thin",
+ "k>",
+ "</thi",
+ "nk>",
+ ];
+ const next = mulberry32(24680);
+ let unclosed = 0;
+ let closed = 0;
+ for (let run = 0; run < 2_000; run += 1) {
+ const chunks: string[] = [];
+ const count = 1 + (next() % 24);
+ for (let i = 0; i < count; i += 1) {
+ chunks.push(alphabet[next() % alphabet.length]);
+ }
+ const seen = assertAgreesOnStream(chunks, `random run ${run}`);
+ unclosed += seen.unclosed;
+ closed += seen.closed;
+ }
+ // Both answers have to occur, or the comparison above would hold for a
+ // constant tracker.
+ assert.equal(unclosed > 1_000, true, `only ${unclosed} unclosed states seen`);
+ assert.equal(closed > 1_000, true, `only ${closed} closed states seen`);
+});
+
+test("tracker agrees with a full rescan on random streams with strips", () => {
+ const alphabet = ["<think>", "</think>", "<", "/", "t", "h", "i", "n", "k", ">", "x"];
+ const next = mulberry32(13579);
+ let unclosed = 0;
+ let closed = 0;
+ let strips = 0;
+ for (let run = 0; run < 2_000; run += 1) {
+ const tracker = createThinkTagTracker();
+ let text = "";
+ const count = 1 + (next() % 16);
+ for (let i = 0; i < count; i += 1) {
+ text += alphabet[next() % alphabet.length];
+ // Cut a suffix off, as the trailing-fragment strip does.
+ if (next() % 3 === 0) {
+ const shorter = text.slice(0, Math.max(0, text.length - (next() % 12)));
+ if (shorter.length < text.length) strips += 1;
+ text = shorter;
+ }
+ const answer = hasUnclosedThinkTag(text);
+ assert.equal(
+ tracker.update(text),
+ answer,
+ `random strip run ${run}: disagreed at step ${i} on ${JSON.stringify(text)}`,
+ );
+ if (answer) unclosed += 1;
+ else closed += 1;
+ }
+ }
+ assert.equal(strips > 1_000, true, `only ${strips} suffixes were removed`);
+ assert.equal(unclosed > 500, true, `only ${unclosed} unclosed states seen`);
+ assert.equal(closed > 500, true, `only ${closed} closed states seen`);
+});
diff --git a/studio/frontend/tests/trailing-template-placeholder.test.ts b/studio/frontend/tests/trailing-template-placeholder.test.ts
new file mode 100644
index 00000000000..5b08de69a2d
--- /dev/null
+++ b/studio/frontend/tests/trailing-template-placeholder.test.ts
@@ -0,0 +1,204 @@
+// 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 {
+ TRAILING_PLACEHOLDER_WINDOW,
+ stripTrailingTemplatePlaceholder,
+} from "../src/features/chat/utils/trailing-template-placeholder.ts";
+
+/**
+ * What the adapter used to run over the whole buffer on every arrival. The
+ * bounded scan must agree with it character for character on anything that fits
+ * in the window, or the strip has changed what reaches the bubble.
+ */
+const UNBOUNDED = /\s*\$\{[^}]*\}\s*$/;
+function stripUnbounded(text: string): string {
+ return text.replace(UNBOUNDED, "");
+}
+
+test("bounded strip matches the unbounded pattern on fixed cases", () => {
+ const cases = [
+ "",
+ " ",
+ "no placeholder here",
+ "trailing brace }",
+ "${}",
+ "${a}",
+ "hello ${name}",
+ "hello ${name} ",
+ "hello ${name}\n\n",
+ "hello\n\n${name}\n",
+ "hello ${name} world",
+ "hello ${name} world}",
+ "a}${b}",
+ "${x${y}",
+ "prefix ${a}${b}",
+ "prefix ${a} ${b}",
+ "${a\nb}",
+ "unterminated ${a",
+ "closed but empty ${ }",
+ "dollar $ alone }",
+ "brace {a}",
+ "$}{",
+ "text ${x} ",
+ "```ts\nconst a = { b: 1 };\n```",
+ "json {\"a\": {\"b\": 1}}",
+ "json {\"a\": {\"b\": 1}} ${c}",
+ ];
+ for (const input of cases) {
+ assert.equal(
+ stripTrailingTemplatePlaceholder(input),
+ stripUnbounded(input),
+ `disagreed on ${JSON.stringify(input)}`,
+ );
+ }
+});
+
+/**
+ * Deterministic pseudo-random generator. A plain `seed * 1103515245` loop is not
+ * usable here: the product runs past 2^53, so the sampled low bits come out
+ * constant and half of any alphabet is never drawn, which is how the first draft
+ * of this test came to compare 20,000 strings the pattern could not match.
+ */
+function mulberry32(seed: number): () => number {
+ let state = seed >>> 0;
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let t = state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return (t ^ (t >>> 14)) >>> 0;
+ };
+}
+
+/**
+ * Random strings over the characters that matter, each ending in a tail the
+ * pattern has a real chance of matching.
+ */
+function* randomInputs(count: number, seed = 20260816): Generator<string> {
+ const alphabet = ["$", "{", "}", " ", "\n", "\t", "a", "b", "x", "${", "a}"];
+ const tails = [
+ "",
+ "${x}",
+ " ${x}",
+ "${}",
+ "\n${a b}\n",
+ "${a",
+ "}${x}",
+ "a}${b}",
+ "${x${y}",
+ " ",
+ "}",
+ "${x} ",
+ ];
+ const next = mulberry32(seed);
+ for (let i = 0; i < count; i += 1) {
+ const length = next() % 40;
+ let out = "";
+ for (let j = 0; j < length; j += 1) {
+ out += alphabet[next() % alphabet.length];
+ }
+ yield out + tails[next() % tails.length];
+ }
+}
+
+test("bounded strip matches the unbounded pattern on random inputs", () => {
+ let checked = 0;
+ let stripped = 0;
+ for (const input of randomInputs(20_000)) {
+ const reference = stripUnbounded(input);
+ assert.equal(
+ stripTrailingTemplatePlaceholder(input),
+ reference,
+ `disagreed on ${JSON.stringify(input)}`,
+ );
+ checked += 1;
+ if (reference !== input) stripped += 1;
+ }
+ assert.equal(checked, 20_000);
+ // Without this the comparison above also holds for an implementation that
+ // returns its argument, which is what the first draft of this test did.
+ assert.equal(
+ stripped > 2_000,
+ true,
+ `only ${stripped} of ${checked} random inputs had anything to strip`,
+ );
+});
+
+test("bounded strip matches the unbounded pattern behind a long reply", () => {
+ // The window makes the scan cheap, but a placeholder at the end of a long
+ // reply still has to be stripped exactly, whatever precedes it.
+ const prefixes = [
+ "word ".repeat(20_000),
+ "}".repeat(5_000),
+ "{".repeat(5_000),
+ `${"a".repeat(50_000)}}`,
+ "$".repeat(5_000),
+ ];
+ for (const prefix of prefixes) {
+ for (const suffix of ["", " ${x}", "\n${x.y}\n", " ${}", " ${a"]) {
+ const input = prefix + suffix;
+ assert.equal(
+ stripTrailingTemplatePlaceholder(input),
+ stripUnbounded(input),
+ `disagreed on ${JSON.stringify(suffix)} after ${prefix.length} chars`,
+ );
+ }
+ }
+});
+
+test("a placeholder past the window is left whole, never cut in half", () => {
+ const inner = "a".repeat(TRAILING_PLACEHOLDER_WINDOW + 100);
+ const input = `answer \${${inner}}`;
+ // The unbounded pattern would take it; this is the documented bound.
+ assert.equal(stripUnbounded(input), "answer");
+ const stripped = stripTrailingTemplatePlaceholder(input);
+ assert.equal(stripped, input, "an oversized fragment must be left alone");
+ // Never acceptable: half a fragment kept, or a result that is not a prefix.
+ assert.equal(input.startsWith(stripped), true);
+});
+
+test("a whitespace run past the window cannot restart the whole-buffer scan", () => {
+ const input = `answer \${x}${" ".repeat(TRAILING_PLACEHOLDER_WINDOW + 100)}`;
+ const stripped = stripTrailingTemplatePlaceholder(input);
+ assert.equal(input.startsWith(stripped), true);
+ assert.equal(stripped, input, "an oversized whitespace run must be left alone");
+});
+
+test("a narrow window only ever strips less than the unbounded pattern", () => {
+ // Whatever the window, the scan may keep text the unbounded pattern would
+ // have removed, but never remove text the unbounded pattern kept.
+ let differed = 0;
+ for (const window of [1, 2, 4, 8, 16]) {
+ for (const input of randomInputs(4_000)) {
+ const bounded = stripTrailingTemplatePlaceholder(input, window);
+ const unbounded = stripUnbounded(input);
+ assert.equal(
+ input.startsWith(bounded),
+ true,
+ `not a prefix for window ${window} on ${JSON.stringify(input)}`,
+ );
+ assert.equal(
+ bounded.length >= unbounded.length,
+ true,
+ `stripped more than the pattern for window ${window} on ${JSON.stringify(input)}`,
+ );
+ assert.equal(
+ bounded.startsWith(unbounded),
+ true,
+ `diverged before the strip for window ${window} on ${JSON.stringify(input)}`,
+ );
+ if (bounded !== input) differed += 1;
+ }
+ }
+ // The property is trivial for a scan that never strips, so the inputs have to
+ // reach the strip for it to mean anything.
+ assert.equal(
+ differed > 1_000,
+ true,
+ `only ${differed} inputs were stripped at all across the narrow windows`,
+ );
+});