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 the streamed reply being flattened on every arrival (#9049)
Daniel Han4f0d691cfc65
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex ce89d20d7f8..42a021d816d 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -167,7 +167,11 @@ import {extractDeltaText,parseAssistantContent,} from "../utils/parse-assistant-content";-import { stripTrailingTemplatePlaceholder } from "../utils/trailing-template-placeholder";+import { createSegmentedAssistantText } from "../utils/incremental-assistant-content";+import {+ createTrailingPlaceholderWatch,+ stripTrailingTemplatePlaceholder,+} from "../utils/trailing-template-placeholder";import { createStreamPublishGate } from "../utils/stream-pacing";import {countReasoningGroups,@@ -4670,11 +4674,18 @@ 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.+ // Reading `cumulativeText` at all costs O(reply): each `+=` builds a cons+ // string and the first read of it flattens the whole reply, so one+ // charCodeAt per arrival is as expensive as a scan. Everything below that+ // used to consult the buffer once per arrival is fed the delta instead,+ // through `appendCumulative`, and the buffer is only read where the reply+ // is actually published.+ //+ // Answers "does the text end inside <think>" from what each arrival adds.const thinkTags = createThinkTagTracker();+ // Answers "could the trailing ${...} strip cut anything" the same way, so+ // the strip itself runs only on an arrival that ends in a fragment.+ const placeholderWatch = createTrailingPlaceholderWatch();// What the cap is measured against: only grows, unlike cumulativeText,// and counts tool-argument deltas, which never reach it.let streamedChars = 0;@@ -4692,6 +4703,31 @@ export function createOpenAIStreamAdapter(text.slice(continuationPartial.length),): text;+ // The parse of everything already streamed, extended by each delta.+ // `mergeContinuation` can rewrite the prefix it is handed, and a rewritten+ // prefix is exactly what an extend-only parse cannot follow, so that one+ // path keeps reparsing the whole reply as before. It is a continuation of+ // an external provider that may repeat itself, not the streaming case.+ const segmentedText = createSegmentedAssistantText({+ trustAppends: !(continuationPartial && repairContinuation),+ });+ // The single place `cumulativeText` grows, so everything derived from it+ // sees the same characters in the same order.+ const appendCumulative = (text: string): void => {+ if (!text) {+ return;+ }+ cumulativeText += text;+ segmentedText.appendText(text);+ thinkTags.append(text);+ placeholderWatch.append(text);+ };+ // A resumed turn starts with the partial already in the buffer. One read+ // of it, once per turn, is what puts the trackers in step with it.+ if (cumulativeText) {+ thinkTags.append(cumulativeText);+ placeholderWatch.append(cumulativeText);+ }// Every streamed yield carries the repaired text, not just the terminal ones:// assistant-ui drops whatever is yielded after an abort, so on Stop the last// STREAMED yield is what gets saved.@@ -4790,23 +4826,25 @@ export function createOpenAIStreamAdapter(}).sort((a, b) => a.cursor - b.cursor || a.index - b.index);+ // The distinct cursors, which are where the text is cut into runs. The+ // runs before them never change again once a later one exists, so only+ // the last one is still growing.+ const boundaries: number[] = [];+ for (const positioned of positionedTools) {+ if (boundaries[boundaries.length - 1] !== positioned.cursor) {+ boundaries.push(positioned.cursor);+ }+ }+ const runs = segmentedText.runs(rawText, boundaries);+const assembled: Array<ReturnType<typeof parseAssistantContent>[number] | ToolCallMessagePart> = [];- let textCursor = 0;let toolIndex = 0;- const appendTextThrough = (nextCursor: number) => {- if (nextCursor <= textCursor) return;- assembled.push(- ...parseAssistantContent(rawText.slice(textCursor, nextCursor)),- );- textCursor = nextCursor;- };-- while (toolIndex < positionedTools.length) {- const cursor = positionedTools[toolIndex].cursor;- appendTextThrough(cursor);+ for (let index = 0; index < boundaries.length; index += 1) {+ assembled.push(...runs[index]);+ const cursor = boundaries[index];while (toolIndex < positionedTools.length &&positionedTools[toolIndex].cursor === cursor@@ -4815,7 +4853,7 @@ export function createOpenAIStreamAdapter(toolIndex += 1;}}- appendTextThrough(rawText.length);+ assembled.push(...runs[boundaries.length]);return pinTextThoughtSignature(assembled);};@@ -4858,7 +4896,7 @@ export function createOpenAIStreamAdapter(};const closeReasoningContent = () => {if (reasoningContentOpen) {- cumulativeText += "</think>";+ appendCumulative("</think>");reasoningContentOpen = false;}reasoningDurationTracker.finishGroup();@@ -6318,30 +6356,38 @@ export function createOpenAIStreamAdapter(if (reasoning) {if (!reasoningContentOpen) {reasoningDurationTracker.startGroup();- cumulativeText += `<think>${reasoning}`;+ appendCumulative(`<think>${reasoning}`);reasoningContentOpen = true;} else {- cumulativeText += reasoning;+ appendCumulative(reasoning);}}if (delta) {if (reasoningContentOpen) {closeReasoningContent();}- cumulativeText += delta;+ appendCumulative(delta);}streamedChars += reasoning.length + delta.length;// Strip a trailing ${...} template-literal fragment from// external streams (mistral magistral occasionally emits one).- if (isExternalRequest) {- cumulativeText =+ // The watch answers from the deltas whether a fragment could be+ // sitting at the end, so the scan itself, which has to touch the+ // buffer and therefore flatten the whole reply, runs only on an+ // arrival that ends in one. It never says no when the scan would+ // cut, so nothing that used to be stripped survives.+ if (isExternalRequest && placeholderWatch.isCandidate()) {+ const stripped =stripTrailingTemplatePlaceholder(cumulativeText);+ if (stripped.length !== cumulativeText.length) {+ cumulativeText = stripped;+ // A suffix went away, so both trackers have to be told; the+ // parse notices by itself, from the length.+ thinkTags.retract(cumulativeText);+ placeholderWatch.retract(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 textEndsInsideThink = thinkTags.endsInsideThink();const assistantContent = liveAssistantContent();// Fallback when no server-side reasoning_summary arrives.diff --git a/studio/frontend/src/features/chat/utils/incremental-assistant-content.ts b/studio/frontend/src/features/chat/utils/incremental-assistant-content.tsnew file mode 100644index 00000000000..ecc5437091b--- /dev/null+++ b/studio/frontend/src/features/chat/utils/incremental-assistant-content.ts@@ -0,0 +1,195 @@+// 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 type { ChatModelRunResult } from "@assistant-ui/react";++import {+ appendReasoningPart,+ appendTextPart,+} from "./parse-assistant-content.ts";++type ContentPart = NonNullable<ChatModelRunResult["content"]>[number];++const THINK_OPEN_TAG = "<think>";+const THINK_CLOSE_TAG = "</think>";++/**+ * Length of the longest suffix of `text` that is a proper prefix of `tag`.+ *+ * Those characters cannot be classified yet: `<thi` at the end of what has+ * arrived is plain text if the reply stops there and the opening of a+ * reasoning block if `nk>` arrives next, so they are held back and reclassified+ * once the next arrival settles them.+ */+function heldBackLength(text: string, tag: string): number {+ const most = Math.min(tag.length - 1, text.length);+ for (let size = most; size > 0; size -= 1) {+ if (text.startsWith(tag.slice(0, size), text.length - size)) {+ return size;+ }+ }+ return 0;+}++/**+ * One run of text between two tool-call boundaries, parsed as it arrives.+ *+ * Reproduces `parseAssistantContent` over the run exactly, including that it+ * coalesces adjacent parts of the same kind and that a run ending inside a+ * `<think>` block yields a reasoning part with no closing tag.+ */+class ParsedRun {+ readonly parts: ContentPart[] = [];+ private insideThink = false;+ private held = "";++ append(delta: string): void {+ if (!delta) {+ return;+ }+ const work = this.held ? this.held + delta : delta;+ this.held = "";+ let cursor = 0;+ for (;;) {+ const tag = this.insideThink ? THINK_CLOSE_TAG : THINK_OPEN_TAG;+ const at = work.indexOf(tag, cursor);+ if (at === -1) {+ break;+ }+ this.commit(work.slice(cursor, at));+ cursor = at + tag.length;+ this.insideThink = !this.insideThink;+ }+ const rest = cursor === 0 ? work : work.slice(cursor);+ const hold = heldBackLength(+ rest,+ this.insideThink ? THINK_CLOSE_TAG : THINK_OPEN_TAG,+ );+ if (hold > 0) {+ this.held = rest.slice(rest.length - hold);+ this.commit(rest.slice(0, rest.length - hold));+ } else {+ this.commit(rest);+ }+ }++ /**+ * The run's parts. The held-back characters are folded in as whatever+ * `parseAssistantContent` would call them if the reply stopped here, so the+ * result is that function's output for every state the run passes through.+ */+ view(): ContentPart[] {+ // A copy even when nothing is held back. The retained parts are the state+ // the next arrival extends, so handing the array itself out would let a+ // caller rewrite what has already been parsed.+ const out = this.parts.slice();+ if (!this.held) {+ return out;+ }+ if (this.insideThink) {+ appendReasoningPart(out, this.held);+ } else {+ appendTextPart(out, this.held);+ }+ return out;+ }++ private commit(text: string): void {+ if (this.insideThink) {+ appendReasoningPart(this.parts, text);+ } else {+ appendTextPart(this.parts, text);+ }+ }+}++export type SegmentedAssistantText = {+ /** Take the characters an arrival added to the reply. */+ appendText(delta: string): void;+ /**+ * Parsed parts for the run before each boundary, then the run after the last+ * one, so the result always has `boundaries.length + 1` entries.+ *+ * `rawText` is only read when the retained state cannot be trusted for it;+ * on the streaming path that is the boundaries changing, which happens once+ * per tool call, not once per arrival.+ */+ runs(rawText: string, boundaries: readonly number[]): ContentPart[][];+};++function sameBoundaries(+ left: readonly number[],+ right: readonly number[],+): boolean {+ if (left.length !== right.length) {+ return false;+ }+ for (let index = 0; index < left.length; index += 1) {+ if (left[index] !== right[index]) {+ return false;+ }+ }+ return true;+}++/**+ * Parse the accumulated reply into content parts without rereading it.+ *+ * The adapter appends to one string per arrival and then parses the whole+ * thing, which is O(reply) per arrival for two reasons: the parse itself, and+ * that `text += delta` builds a cons string whose first read flattens it. This+ * keeps the parse of everything already seen and extends it with the delta, so+ * neither cost is paid again.+ *+ * The retained state describes an append-only reply. Anything else, a rewrite+ * of the prefix or a suffix removed or a tool call landing behind the end,+ * shows up as a length or boundary mismatch and rebuilds from `rawText`. That+ * costs one full parse, on the arrivals that do it, which is the behaviour+ * this replaces.+ */+export function createSegmentedAssistantText({+ trustAppends = true,+}: { trustAppends?: boolean } = {}): SegmentedAssistantText {+ let runs: ParsedRun[] = [new ParsedRun()];+ let boundaries: number[] = [];+ let length = 0;++ const rebuild = (+ rawText: string,+ nextBoundaries: readonly number[],+ ): void => {+ runs = [];+ boundaries = [...nextBoundaries];+ length = rawText.length;+ let from = 0;+ for (const boundary of boundaries) {+ const run = new ParsedRun();+ run.append(rawText.slice(from, boundary));+ runs.push(run);+ from = boundary;+ }+ const last = new ParsedRun();+ last.append(rawText.slice(from));+ runs.push(last);+ };++ return {+ appendText(delta: string): void {+ if (!delta) {+ return;+ }+ runs[runs.length - 1].append(delta);+ length += delta.length;+ },+ runs(rawText: string, nextBoundaries: readonly number[]): ContentPart[][] {+ if (+ !trustAppends ||+ rawText.length !== length ||+ !sameBoundaries(boundaries, nextBoundaries)+ ) {+ rebuild(rawText, nextBoundaries);+ }+ return runs.map((run) => run.view());+ },+ };+}diff --git a/studio/frontend/src/features/chat/utils/parse-assistant-content.ts b/studio/frontend/src/features/chat/utils/parse-assistant-content.tsindex 40d0d14d248..11277efeab5 100644--- a/studio/frontend/src/features/chat/utils/parse-assistant-content.ts+++ b/studio/frontend/src/features/chat/utils/parse-assistant-content.ts@@ -83,7 +83,7 @@ export function extractDeltaText(delta: unknown): {// 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 {+export function appendTextPart(parts: ContentPart[], text: string): void {if (!text) return;const last = parts.at(-1);if (last?.type === "text") {@@ -93,7 +93,7 @@ function appendTextPart(parts: ContentPart[], text: string): void {parts.push({ type: "text", text });}-function appendReasoningPart(parts: ContentPart[], text: string): void {+export function appendReasoningPart(parts: ContentPart[], text: string): void {if (!text) return;const last = parts.at(-1);if (last?.type === "reasoning") {@@ -149,61 +149,87 @@ const THINK_TAG_OVERLAP =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.+ * Take the characters an arrival added. Reads `delta` and the seven+ * characters in front of it, never the accumulated reply.*/- update(text: string): boolean;+ append(delta: string): void;+ /**+ * Take back the suffix a rewrite removed. `text` is the buffer AFTER the+ * removal, and is read only when a tag left with the suffix or the retained+ * overlap has to be refilled, both of which the trailing template-literal+ * strip makes rare.+ */+ retract(text: string): void;+ /**+ * Whether the accumulated text ends inside a `<think>` block, that is, what+ * `hasUnclosedThinkTag` returns for the same text.+ */+ endsInsideThink(): boolean;};/**- * Track `hasUnclosedThinkTag` across a stream without rereading the buffer.+ * Track `hasUnclosedThinkTag` across a stream without reading 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.+ * arrival costs O(reply^2) over a reply. Reading the buffer at all costs that+ * much, even for one character: `text += delta` builds a cons string, and the+ * next read of it flattens the whole thing. So this takes the delta rather+ * than the buffer, and keeps the last seven characters itself, which is the+ * most a tag split across arrivals can hide in front of one. A `<think>`+ * delivered one character at a time over seven arrivals is still 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;+ // Characters taken so far; the two indices are the last position of each tag+ // within them, or -1, exactly as `lastIndexOf` reports.+ let length = 0;let lastOpen = -1;let lastClose = -1;+ // The final `THINK_TAG_OVERLAP` characters, held flat so the next arrival can+ // be searched together with the tag prefix it may complete.+ let overlap = "";++ const refindWithin = (text: string): void => {+ 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);+ }+ };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);- }+ append(delta: string): void {+ if (!delta) {+ return;+ }+ const window = overlap + delta;+ const from = length - overlap.length;+ // A tag re-found inside the overlap is the one already recorded, so it+ // can only reproduce the index it produced last time.+ const openAt = window.lastIndexOf(THINK_OPEN_TAG);+ if (openAt !== -1) {+ lastOpen = Math.max(lastOpen, from + openAt);}- scanned = text.length;+ const closeAt = window.lastIndexOf(THINK_CLOSE_TAG);+ if (closeAt !== -1) {+ lastClose = Math.max(lastClose, from + closeAt);+ }+ length += delta.length;+ overlap =+ window.length <= THINK_TAG_OVERLAP+ ? window+ : window.slice(window.length - THINK_TAG_OVERLAP);+ },+ retract(text: string): void {+ refindWithin(text);+ length = text.length;+ overlap =+ text.length <= THINK_TAG_OVERLAP+ ? text+ : text.slice(text.length - THINK_TAG_OVERLAP);+ },+ endsInsideThink(): boolean {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.tsindex 552d960cce3..ccf6c9e08fa 100644--- a/studio/frontend/src/features/chat/utils/trailing-template-placeholder.ts+++ b/studio/frontend/src/features/chat/utils/trailing-template-placeholder.ts@@ -72,3 +72,110 @@ export function stripTrailingTemplatePlaceholder(}return text.slice(0, from + scanFrom + match.index);}++/**+ * How far back a re-seed looks after a strip. The scan above never reads+ * further back than `end - 1 - window`, and `end` is itself no further back+ * than `length - window`, so everything it can reach lives in the last+ * `2 * window` characters. The extra two cover the `${` straddling that edge.+ */+const RESEED_WINDOW = 2 * TRAILING_PLACEHOLDER_WINDOW + 2;++const DOLLAR_BRACE = "${";++export type TrailingPlaceholderWatch = {+ /** Take the characters an arrival added. Reads `delta`, never the buffer. */+ append(delta: string): void;+ /** Take back the suffix a strip removed. `text` is the buffer after it. */+ retract(text: string): void;+ /**+ * Whether `stripTrailingTemplatePlaceholder` could still cut something.+ *+ * Never false when it would, so the strip can be skipped outright whenever+ * this is false. It may be true when the strip then cuts nothing, which+ * costs one wasted scan on an arrival that already looked like a fragment.+ */+ isCandidate(): boolean;+};++/**+ * Decide whether the trailing `${...}` strip has anything to do, from the+ * deltas alone.+ *+ * `stripTrailingTemplatePlaceholder` is bounded, but it still has to touch the+ * end of the accumulated reply, and touching it at all flattens the cons+ * string that `text += delta` built, which costs O(reply) per arrival. The+ * pattern needs the last non-whitespace character to be `}` and a `${` in+ * front of it with no `}` in between, and both facts follow from the deltas:+ * a reply that never ends in a brace, which is almost every arrival of almost+ * every reply, is rejected without the buffer being read.+ */+export function createTrailingPlaceholderWatch(): TrailingPlaceholderWatch {+ let length = 0;+ // The last non-whitespace character, or "" when there is none.+ let lastNonWhitespace = "";+ // Index of the last `${`, of the last `}`, and of the `}` before that one.+ let lastDollarBrace = -1;+ let lastCloseBrace = -1;+ let previousCloseBrace = -1;+ // One character, so a `${` split across two arrivals is still seen.+ let overlap = "";++ const scan = (window: string, from: number): void => {+ for (let index = 0; index < window.length; index += 1) {+ const character = window[index];+ if (character === CLOSE_BRACE) {+ previousCloseBrace = lastCloseBrace;+ lastCloseBrace = from + index;+ } else if (+ character === "{" &&+ index > 0 &&+ window[index - 1] === DOLLAR_BRACE[0]+ ) {+ lastDollarBrace = from + index - 1;+ }+ if (!WHITESPACE.test(character)) {+ lastNonWhitespace = character;+ }+ }+ };++ return {+ append(delta: string): void {+ if (!delta) {+ return;+ }+ // The `${` straddling the boundary is the one thing `delta` alone cannot+ // show, because its `$` may have arrived last time.+ if (overlap === DOLLAR_BRACE[0] && delta[0] === "{") {+ lastDollarBrace = length - 1;+ }+ scan(delta, length);+ length += delta.length;+ overlap = delta[delta.length - 1];+ },+ retract(text: string): void {+ length = text.length;+ lastNonWhitespace = "";+ lastDollarBrace = -1;+ lastCloseBrace = -1;+ previousCloseBrace = -1;+ overlap = "";+ // Only what the strip itself could reach. A `${` or `}` further back+ // than this cannot take part in a match, so forgetting it cannot hide+ // one: the strip would not look there either.+ const from = Math.max(0, text.length - RESEED_WINDOW);+ scan(text.slice(from), from);+ if (text.length > 0) {+ overlap = text[text.length - 1];+ }+ },+ isCandidate(): boolean {+ return (+ lastNonWhitespace === CLOSE_BRACE &&+ lastDollarBrace > previousCloseBrace &&+ lastDollarBrace < lastCloseBrace+ );+ },+ };+}diff --git a/studio/frontend/tests/chat-adapter-scan-cost.test.ts b/studio/frontend/tests/chat-adapter-scan-cost.test.tsindex 122bbe3eaa4..c24c1d8d153 100644--- a/studio/frontend/tests/chat-adapter-scan-cost.test.ts+++ b/studio/frontend/tests/chat-adapter-scan-cost.test.ts@@ -5,11 +5,16 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";+import { createSegmentedAssistantText } from "../src/features/chat/utils/incremental-assistant-content.ts";import {createThinkTagTracker,hasUnclosedThinkTag,+ parseAssistantContent,} from "../src/features/chat/utils/parse-assistant-content.ts";-import { stripTrailingTemplatePlaceholder } from "../src/features/chat/utils/trailing-template-placeholder.ts";+import {+ createTrailingPlaceholderWatch,+ stripTrailingTemplatePlaceholder,+} from "../src/features/chat/utils/trailing-template-placeholder.ts";/*** Complexity tests, not timing tests: they count the characters the scans look@@ -18,11 +23,13 @@ import { stripTrailingTemplatePlaceholder } from "../src/features/chat/utils/tra** String replace / lastIndexOf / indexOf the receiver's length* String slice the length it produces+ * String startsWith the length it compares* 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.+ * `test` is in the list because the bounded strip walks the trailing+ * whitespace run one character at a time, and the placeholder watch walks each+ * delta the same way; each of those reads shows up as a one-character subject,+ * so a walk that ran away would be counted, not hidden.*/type Counted = { chars: number };@@ -32,6 +39,7 @@ function withScanAccounting<T>(body: () => T): { result: T; chars: number } {const realLastIndexOf = String.prototype.lastIndexOf;const realIndexOf = String.prototype.indexOf;const realSlice = String.prototype.slice;+ const realStartsWith = String.prototype.startsWith;const realExec = RegExp.prototype.exec;const realTest = RegExp.prototype.test;@@ -60,6 +68,14 @@ function withScanAccounting<T>(body: () => T): { result: T; chars: number } {counted.chars += out.length;return out;};+ String.prototype.startsWith = function countingStartsWith(+ this: string,+ search: string,+ position?: number,+ ): boolean {+ counted.chars += String(search).length;+ return realStartsWith.call(this, search, position);+ } as unknown as typeof realStartsWith;RegExp.prototype.exec = function countingExec(this: RegExp,subject: string,@@ -83,6 +99,7 @@ function withScanAccounting<T>(body: () => T): { result: T; chars: number } {String.prototype.lastIndexOf = realLastIndexOf;String.prototype.indexOf = realIndexOf;String.prototype.slice = realSlice;+ String.prototype.startsWith = realStartsWith;RegExp.prototype.exec = realExec;RegExp.prototype.test = realTest;}@@ -164,6 +181,53 @@ function runThink(return unclosed;}+/**+ * Everything the adapter does per arrival, in the order it does it: extend the+ * reply, decide whether a trailing fragment needs stripping, ask whether the+ * text ends inside a think block, and rebuild the content parts.+ *+ * The point of this shape is that it is driven by the deltas, exactly as the+ * adapter is. A version of any of these that wanted the whole buffer would+ * show up as a cost that grows with the square of the reply.+ */+function runArrivalPath(arrivals: string[]): number {+ const thinkTags = createThinkTagTracker();+ const watch = createTrailingPlaceholderWatch();+ const segmented = createSegmentedAssistantText();+ let text = "";+ let sink = 0;+ for (const chunk of arrivals) {+ text += chunk;+ thinkTags.append(chunk);+ watch.append(chunk);+ segmented.appendText(chunk);+ if (watch.isCandidate()) {+ const stripped = stripTrailingTemplatePlaceholder(text);+ if (stripped.length !== text.length) {+ text = stripped;+ thinkTags.retract(text);+ watch.retract(text);+ }+ }+ if (thinkTags.endsInsideThink()) sink += 1;+ sink += segmented.runs(text, []).length;+ }+ return sink;+}++/** The same per arrival, the way it was done before: reparse the whole reply. */+function runArrivalPathRereading(arrivals: string[]): number {+ let text = "";+ let sink = 0;+ for (const chunk of arrivals) {+ text += chunk;+ text = stripTrailingTemplatePlaceholder(text);+ if (hasUnclosedThinkTag(text)) sink += 1;+ sink += parseAssistantContent(text).length;+ }+ return sink;+}+const SMALL = 16_000;const LARGE = 32_000;@@ -212,14 +276,17 @@ test("the trailing placeholder strip is linear in the reply length", () => {});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 drive = () => {const tracker = createThinkTagTracker();- return (text: string) => tracker.update(text);- });+ let seen = 0;+ return (text: string) => {+ tracker.append(text.slice(seen));+ seen = text.length;+ return tracker.endsInsideThink();+ };+ };+ const small = thinkCost(SMALL, drive);+ const large = thinkCost(LARGE, drive);const growth = large / small;assert.equal(growth < 2.5,@@ -250,6 +317,50 @@ test("think tag tracking is linear in the reply length", () => {);});+test("the whole per-arrival path is linear in the reply length", () => {+ // The three scans above are each linear on their own; this is the one that+ // says so about the sequence the adapter actually runs, parse included. It+ // is the guard against any future arrival-time step that wants the whole+ // buffer, which is the shape every defect on this path has had.+ const cost = (chars: number): number => {+ const arrivals = arrivalsOf(buildReply(chars));+ return withScanAccounting(() => runArrivalPath(arrivals)).chars;+ };+ const small = cost(SMALL);+ const large = cost(LARGE);+ const growth = large / small;+ assert.equal(+ growth < 2.5,+ true,+ `the per-arrival path grew ${growth.toFixed(2)}x for twice the reply (${small} -> ${large} chars read); that is not linear`,+ );+ assert.equal(+ large < LARGE * 30,+ true,+ `the per-arrival path read ${large} chars for a ${LARGE} character reply`,+ );++ // And the shape it replaces, measured the same way, so the test says what it+ // is guarding against rather than only asserting a number.+ const rereadSmall = withScanAccounting(() =>+ runArrivalPathRereading(arrivalsOf(buildReply(SMALL))),+ ).chars;+ const rereadLarge = withScanAccounting(() =>+ runArrivalPathRereading(arrivalsOf(buildReply(LARGE))),+ ).chars;+ const rereadGrowth = rereadLarge / rereadSmall;+ assert.equal(+ rereadGrowth > 3.5,+ true,+ `rereading grew ${rereadGrowth.toFixed(2)}x, so this test is no longer measuring the difference it was written for`,+ );+ assert.equal(+ large * 10 < rereadLarge,+ true,+ `the per-arrival path read ${large} chars against ${rereadLarge} for rereading; expected at least 10x fewer`,+ );+});+// ------------------------------------------------------------ source pins ---const ADAPTER = readFileSync(@@ -289,37 +400,179 @@ test("the adapter strips the trailing fragment through the bounded scan", () =>);});-test("the adapter asks the tracker once per arrival, not inside a condition", () => {+test("the reply only grows through the one call that keeps the trackers in step", () => {+ // The tracker, the placeholder watch and the incremental parse are all fed+ // the delta rather than the buffer, so each of them is only correct if it is+ // told about every character the reply gains. A second place that appended+ // to `cumulativeText` directly would leave all three describing text that no+ // longer matches, and nothing else in the file would notice.const source = withoutComments(ADAPTER);- assert.doesNotMatch(++ const appends = source.match(/cumulativeText\s*\+=/g) ?? [];+ assert.equal(+ appends.length,+ 1,+ `the reply is appended to in ${appends.length} places; every append has to go through appendCumulative so the trackers see it`,+ );+ assert.match(source,- /hasUnclosedThinkTag\(/,- "the whole buffer is being reread; use the tracker",+ /const appendCumulative = \(text: string\): void => \{\s*if \(!text\) \{\s*return;\s*\}\s*cumulativeText \+=/,+ "the one append site is not appendCumulative",+ );++ // Everything appendCumulative drives has to be driven from it, or the append+ // above is telling only some of them.+ for (const fed of [+ "segmentedText.appendText(text)",+ "thinkTags.append(text)",+ "placeholderWatch.append(text)",+ ]) {+ assert.equal(+ source.includes(fed),+ true,+ `appendCumulative does not feed ${fed}`,+ );+ }+});++/** The adapter between two anchors, without its comments. */+function regionOf(from: string, to: string, maxChars = 60_000): string {+ const start = ADAPTER.indexOf(from);+ assert.notEqual(start, -1, `"${from}" is gone; this test needs rewriting`);+ const end = ADAPTER.indexOf(to, start);+ assert.notEqual(end, -1, `"${to}" is gone; this test needs rewriting`);+ assert.ok(+ end - start < maxChars,+ `the region from "${from}" to "${to}" is ${end - start} chars; an anchor has drifted and this test needs rewriting`,+ );+ return withoutComments(ADAPTER.slice(start, end));+}++test("the arrival loop touches the reply only in ways that cannot flatten it", () => {+ // The cost on this path is not how many characters are read. `text += delta`+ // leaves a cons string, and the whole reply is copied the first time anything+ // forces it flat, which is any character access and any slice other than the+ // whole-string one. So one `charCodeAt` per arrival costs the same as a full+ // scan, and the character counting above cannot tell them apart: both read+ // the same characters. Measured over a 220,000 character reply, a per-arrival+ // `charCodeAt` is about 1000x a per-arrival append.+ //+ // Hence an allow list rather than a search for known-bad spellings: every+ // mention of the buffer inside the loop has to be one that V8 answers without+ // copying, or one that has already been gated behind a check that answers+ // from the deltas.+ const loop = regionOf(+ "for await (const chunk of stream) {",+ "} catch (streamError) {",+ );++ // The strip is the one step allowed to flatten, so it and the repairs that+ // follow a cut are checked as a block and then taken out of the scan below.+ const stripStart = loop.indexOf(+ "if (isExternalRequest && placeholderWatch.isCandidate()) {",+ );+ assert.notEqual(+ stripStart,+ -1,+ "the strip is no longer gated by the watch, so it flattens on every arrival",+ );+ const stripEnd = loop.indexOf("\n }", stripStart);+ assert.notEqual(stripEnd, -1, "the strip block's end is gone");+ const stripBlock = loop.slice(stripStart, stripEnd);+ // Both trackers have to be repaired when a cut happens, and only then: a cut+ // has already flattened the buffer, so reading it again there is free.+ for (const repair of [+ "thinkTags.retract(cumulativeText)",+ "placeholderWatch.retract(cumulativeText)",+ ]) {+ assert.equal(+ stripBlock.includes(repair),+ true,+ `${repair} is not inside the strip block, so it runs on arrivals that never cut`,+ );+ }+ const outsideStrip = loop.slice(0, stripStart) + loop.slice(stripEnd);++ const allowed = [+ // `length` is stored on the cons string, so it never forces a copy.+ "cumulativeText.length",+ ];++ const mentions: string[] = [];+ for (const line of outsideStrip.split("\n")) {+ if (!line.includes("cumulativeText")) {+ continue;+ }+ if (allowed.some((form) => line.includes(form))) {+ continue;+ }+ mentions.push(line.trim());+ }+ assert.deepEqual(+ mentions,+ [],+ `these lines touch the accumulated reply on every arrival, which copies the whole reply each time:\n ${mentions.join("\n ")}`,);- const updates = source.match(/thinkTags\.update\(/g) ?? [];+ // And the loop still does the work, so the list above cannot pass by the+ // buffer having left the loop entirely.assert.equal(- updates.length,- 1,- "the tracker has to see every state the buffer passes through, so exactly one call site",+ stripBlock.includes("stripTrailingTemplatePlaceholder(cumulativeText)"),+ true,+ "the strip is gone from the loop; this test is no longer guarding anything",);+ assert.equal(+ outsideStrip.includes("cumulativeText.length"),+ true,+ "the loop no longer reads the reply's length; this test needs rewriting",+ );+});- // 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(+test("nothing on the arrival path is handed the accumulated reply", () => {+ // Reading the buffer at all flattens the cons string that the appends built,+ // which costs the whole reply, so a scan that is bounded is still quadratic+ // if it is given `cumulativeText`. The three per-arrival steps therefore take+ // the delta, and the one that cannot, the strip, runs behind a check that+ // answers from the deltas.+ const source = withoutComments(ADAPTER);++ assert.doesNotMatch(source,- /const textEndsInsideThink = thinkTags\.update\(cumulativeText\);/,+ /hasUnclosedThinkTag\(/,+ "the whole buffer is being reread; use the tracker",);- assert.match(source, /&&\s*!textEndsInsideThink\s*\)/);+ for (const perArrival of [+ /thinkTags\.append\(cumulativeText\)/,+ /placeholderWatch\.append\(cumulativeText\)/,+ /segmentedText\.appendText\(cumulativeText\)/,+ ]) {+ // The seed of a resumed turn is the exception, and it is outside the loop.+ const inLoop = source+ .slice(source.indexOf("const appendCumulative"))+ .replace(/if \(cumulativeText\) \{[\s\S]*?\n {6}\}/, "");+ assert.doesNotMatch(+ inLoop,+ perArrival,+ "a per-arrival step is being handed the whole reply instead of the delta",+ );+ }- 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);+ // The strip is the one step that has to touch the buffer when it fires, so+ // it fires only when the watch says a fragment could be there.+ assert.match(+ source,+ /if \(isExternalRequest && placeholderWatch\.isCandidate\(\)\) \{/,+ "the strip is running unconditionally again",+ );+ const candidate = source.indexOf("placeholderWatch.isCandidate()");+ const strip = source.indexOf(+ "stripTrailingTemplatePlaceholder(cumulativeText)",+ );+ const ask = source.indexOf("thinkTags.endsInsideThink()");+ assert.equal(candidate !== -1 && strip !== -1 && ask !== -1, true);assert.equal(- strip < update && update < ask,+ candidate < strip && strip < ask,true,- "the tracker must be updated after the strip and before the buffer is asked about",+ "the buffer must be asked about only after the strip has settled it",);});diff --git a/studio/frontend/tests/chat-stream-publish-gate.test.ts b/studio/frontend/tests/chat-stream-publish-gate.test.tsindex b574d9ac3e9..82a280a5923 100644--- a/studio/frontend/tests/chat-stream-publish-gate.test.ts+++ b/studio/frontend/tests/chat-stream-publish-gate.test.ts@@ -294,7 +294,11 @@ test("the gate paces the publish, not the bookkeeping before it", () => {// only the yield to assistant-ui is coalesced. Pacing the interpretation too// is what dragged reasoning timing, split tags, server summaries and replay// metadata into a change that is about paint cost.- const append = loop.indexOf("cumulativeText += delta");+ // The append goes through `appendCumulative`, which is what keeps the+ // delta-fed think tracker, placeholder watch and incremental parse in step+ // with the reply. What this test cares about is unchanged: it happens in the+ // loop, on every arrival, before the rebuild reads it.+ const append = loop.indexOf("appendCumulative(delta)");const rebuild = loop.indexOf("const assistantContent = liveAssistantContent()",);diff --git a/studio/frontend/tests/incremental-assistant-content.test.ts b/studio/frontend/tests/incremental-assistant-content.test.tsnew file mode 100644index 00000000000..763770035fd--- /dev/null+++ b/studio/frontend/tests/incremental-assistant-content.test.ts@@ -0,0 +1,258 @@+// 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 { createSegmentedAssistantText } from "../src/features/chat/utils/incremental-assistant-content.ts";+import { parseAssistantContent } from "../src/features/chat/utils/parse-assistant-content.ts";++/**+ * What the adapter did before: cut the whole reply at the tool cursors and+ * parse each run from scratch. The incremental parse has to agree with this+ * for every state a stream passes through, which is what the sweep below+ * checks, so this is the oracle and must stay a plain rewrite of the original.+ */+function referenceRuns(+ rawText: string,+ boundaries: readonly number[],+): ReturnType<typeof parseAssistantContent>[] {+ const out: ReturnType<typeof parseAssistantContent>[] = [];+ let from = 0;+ for (const boundary of boundaries) {+ out.push(parseAssistantContent(rawText.slice(from, boundary)));+ from = boundary;+ }+ out.push(parseAssistantContent(rawText.slice(from)));+ return out;+}++// ---------------------------------------------------------------- random ---++function makeRandom(seed: number): () => number {+ let value = seed >>> 0;+ return () => {+ value = (value * 1664525 + 1013904223) >>> 0;+ return value / 0x100000000;+ };+}++// Pieces chosen so a tag can be split at every offset, and so text that only+// looks like a tag ("<thi", "</thin", "<<think>") is generated often.+const PIECES = [+ "a",+ " ",+ "\n",+ "<",+ "</",+ "<t",+ "<th",+ "<thi",+ "<thin",+ "<think",+ "<think>",+ "hink>",+ "think>",+ "k>",+ ">",+ "/think>",+ "</think>",+ "</thi",+ "word ",+ "<think></think>",+ "<think>x",+ "x</think>",+ "",+];++function randomReply(random: () => number, pieces: number): string {+ let out = "";+ for (let index = 0; index < pieces; index += 1) {+ out += PIECES[Math.floor(random() * PIECES.length)];+ }+ return out;+}++function randomArrivals(random: () => number, text: string): string[] {+ const out: string[] = [];+ let at = 0;+ while (at < text.length) {+ const size = 1 + Math.floor(random() * 5);+ out.push(text.slice(at, at + size));+ at += size;+ }+ return out;+}++// ------------------------------------------------------------------ tests ---++test("the incremental parse matches a full reparse at every arrival", () => {+ const CASES = 3000;+ let states = 0;+ for (let seed = 1; seed <= CASES; seed += 1) {+ const random = makeRandom(seed);+ const text = randomReply(random, 1 + Math.floor(random() * 20));+ const arrivals = randomArrivals(random, text);+ const segmented = createSegmentedAssistantText();+ let accumulated = "";+ for (const arrival of arrivals) {+ accumulated += arrival;+ segmented.appendText(arrival);+ states += 1;+ assert.deepEqual(+ segmented.runs(accumulated, []),+ referenceRuns(accumulated, []),+ `seed ${seed}: diverged at ${JSON.stringify(accumulated)}`,+ );+ }+ }+ assert.equal(states > 10_000, true, `only ${states} states exercised`);+});++test("the incremental parse matches a full reparse across tool boundaries", () => {+ const CASES = 3000;+ let boundaryStates = 0;+ for (let seed = 1; seed <= CASES; seed += 1) {+ const random = makeRandom(seed + 500_000);+ const text = randomReply(random, 1 + Math.floor(random() * 20));+ const arrivals = randomArrivals(random, text);+ const segmented = createSegmentedAssistantText();+ let accumulated = "";+ const boundaries: number[] = [];+ for (const arrival of arrivals) {+ accumulated += arrival;+ segmented.appendText(arrival);+ // A tool call lands at the end of the reply as it stands, which is the+ // only place the adapter puts one.+ if (random() < 0.2) {+ if (boundaries[boundaries.length - 1] !== accumulated.length) {+ boundaries.push(accumulated.length);+ boundaryStates += 1;+ }+ }+ assert.deepEqual(+ segmented.runs(accumulated, boundaries),+ referenceRuns(accumulated, boundaries),+ `seed ${seed}: diverged at ${JSON.stringify(accumulated)} with boundaries ${boundaries.join(",")}`,+ );+ }+ }+ assert.equal(+ boundaryStates > 1000,+ true,+ `only ${boundaryStates} boundaries exercised`,+ );+});++test("the incremental parse recovers when a suffix is removed", () => {+ const CASES = 1500;+ let truncations = 0;+ for (let seed = 1; seed <= CASES; seed += 1) {+ const random = makeRandom(seed + 900_000);+ const text = randomReply(random, 2 + Math.floor(random() * 20));+ const arrivals = randomArrivals(random, text);+ const segmented = createSegmentedAssistantText();+ let accumulated = "";+ for (const arrival of arrivals) {+ accumulated += arrival;+ segmented.appendText(arrival);+ if (random() < 0.15 && accumulated.length > 1) {+ // The trailing placeholder strip is the only thing that shortens the+ // buffer, and it always takes a suffix.+ accumulated = accumulated.slice(+ 0,+ Math.floor(random() * accumulated.length),+ );+ truncations += 1;+ }+ assert.deepEqual(+ segmented.runs(accumulated, []),+ referenceRuns(accumulated, []),+ `seed ${seed}: diverged after truncation at ${JSON.stringify(accumulated)}`,+ );+ }+ }+ assert.equal(+ truncations > 500,+ true,+ `only ${truncations} truncations exercised`,+ );+});++test("a rewritten prefix is reparsed rather than extended", () => {+ // What `mergeContinuation` does to an external continuation. The cache is+ // built with the fast path off for that case, so it must still be right.+ const segmented = createSegmentedAssistantText({ trustAppends: false });+ segmented.appendText("<think>one</think>two");+ assert.deepEqual(+ segmented.runs("<think>ONE</think>two", []),+ referenceRuns("<think>ONE</think>two", []),+ );+ // Same length, different characters: the length check alone cannot see this,+ // which is why that path does not rely on it.+ assert.deepEqual(+ segmented.runs("<think>xxx</think>two", []),+ referenceRuns("<think>xxx</think>two", []),+ );+});++test("held-back characters are reclassified when the tag completes", () => {+ const segmented = createSegmentedAssistantText();+ segmented.appendText("hello<thi");+ // Nothing has said this is a tag yet, so it reads as text.+ assert.deepEqual(segmented.runs("hello<thi", []), [+ [{ type: "text", text: "hello<thi" }],+ ]);+ segmented.appendText("nk>secret");+ assert.deepEqual(segmented.runs("hello<think>secret", []), [+ [+ { type: "text", text: "hello" },+ { type: "reasoning", text: "secret" },+ ],+ ]);+});++test("the parts a run hands out are not shared with its retained state", () => {+ const segmented = createSegmentedAssistantText();+ segmented.appendText("one");+ const first = segmented.runs("one", []);+ first[0][0] = { type: "text", text: "clobbered" };+ segmented.appendText(" two");+ assert.deepEqual(segmented.runs("one two", []), [+ [{ type: "text", text: "one two" }],+ ]);+});++test("a tool call before any text leaves an empty run in front of it", () => {+ // The adapter gives a tool part the reply's length as its cursor, so a tool+ // call that arrives before the model has written anything sits at 0. The run+ // in front of it is empty and must contribute no parts at all, not an empty+ // text part.+ const segmented = createSegmentedAssistantText();+ assert.deepEqual(segmented.runs("", [0]), referenceRuns("", [0]));+ segmented.appendText("after the tool");+ assert.deepEqual(+ segmented.runs("after the tool", [0]),+ referenceRuns("after the tool", [0]),+ );+ assert.deepEqual(segmented.runs("after the tool", [0]), [+ [],+ [{ type: "text", text: "after the tool" }],+ ]);+});++test("a think block split by a tool boundary parses as the adapter parses it", () => {+ // The reference cuts the text at the cursor and parses each side on its own,+ // so the opening tag on the near side leaves an unclosed reasoning part and+ // the far side starts fresh, as text. That is the existing behaviour, odd as+ // it looks, and the incremental parse has to reproduce it rather than fix it.+ const segmented = createSegmentedAssistantText();+ segmented.appendText("<think>before");+ segmented.appendText("after</think> done");+ const text = "<think>beforeafter</think> done";+ assert.deepEqual(segmented.runs(text, [13]), referenceRuns(text, [13]));+ assert.deepEqual(segmented.runs(text, [13]), [+ [{ type: "reasoning", text: "before" }],+ [{ type: "text", text: "after</think> done" }],+ ]);+});diff --git a/studio/frontend/tests/think-tag-tracker.test.ts b/studio/frontend/tests/think-tag-tracker.test.tsindex 48cacc24044..59facca2219 100644--- a/studio/frontend/tests/think-tag-tracker.test.ts+++ b/studio/frontend/tests/think-tag-tracker.test.ts@@ -10,15 +10,38 @@ import {} 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.+ * The tracker takes deltas, because reading the accumulated buffer at all+ * costs O(reply) per arrival. The cases below are written against the buffer,+ * so this maps a buffer to the calls the adapter makes for it: an arrival+ * appends what it added, and the trailing-fragment strip retracts to what it+ * left behind.+ */+function bufferTracker(): { update(text: string): boolean } {+ const tracker = createThinkTagTracker();+ let seen = "";+ return {+ update(text: string): boolean {+ if (text.length >= seen.length) {+ tracker.append(text.slice(seen.length));+ } else {+ tracker.retract(text);+ }+ seen = text;+ return tracker.endsInsideThink();+ },+ };+}++/**+ * Feed `chunks` in order and assert the tracker agrees with a full rescan+ * after every one of them. `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();+ const tracker = bufferTracker();let text = "";let unclosed = 0;let closed = 0;@@ -116,7 +139,7 @@ test("a near miss is not mistaken for a tag", () => {});test("a stream seeded with a continuation partial is tracked", () => {- const tracker = createThinkTagTracker();+ const tracker = bufferTracker();let text = "<think>resumed reasoning";assert.equal(tracker.update(text), hasUnclosedThinkTag(text));text += "</think> answer";@@ -150,7 +173,7 @@ test("a suffix removed from the buffer is accounted for", () => {},];for (const { steps, label } of cases) {- const tracker = createThinkTagTracker();+ const tracker = bufferTracker();for (const [index, text] of steps.entries()) {assert.equal(tracker.update(text),@@ -162,9 +185,9 @@ test("a suffix removed from the buffer is accounted for", () => {});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();+ // What the adapter actually does: append the delta, strip a trailing+ // fragment, then ask once. Only the post-strip buffer is ever seen.+ const tracker = bufferTracker();const deltas = ["<think>","reasoning ",@@ -247,7 +270,7 @@ test("tracker agrees with a full rescan on random streams with strips", () => {let closed = 0;let strips = 0;for (let run = 0; run < 2_000; run += 1) {- const tracker = createThinkTagTracker();+ const tracker = bufferTracker();let text = "";const count = 1 + (next() % 16);for (let i = 0; i < count; i += 1) {@@ -272,3 +295,31 @@ test("tracker agrees with a full rescan on random streams with strips", () => {assert.equal(unclosed > 500, true, `only ${unclosed} unclosed states seen`);assert.equal(closed > 500, true, `only ${closed} closed states seen`);});++test("the adapter's own order, append the delta then retract the strip, is tracked", () => {+ // The wrapper above only ever sees the buffer a strip left behind, so it+ // hides the two-call sequence the adapter really makes. This drives the+ // tracker directly: every delta is appended whole, and only then is the+ // fragment taken back off.+ const random = mulberry32(20260817);+ const alphabet = ["<think>", "</think>", "x", " ", "<thi", "nk>", "}", "${a}"];+ for (let seed = 0; seed < 400; seed += 1) {+ const tracker = createThinkTagTracker();+ let text = "";+ for (let step = 0; step < 24; step += 1) {+ const delta = alphabet[random() % alphabet.length];+ text += delta;+ tracker.append(delta);+ const stripped = text.replace(/\s*\$\{[^}]*\}\s*$/, "");+ if (stripped.length !== text.length) {+ text = stripped;+ tracker.retract(text);+ }+ assert.equal(+ tracker.endsInsideThink(),+ hasUnclosedThinkTag(text),+ `seed ${seed} step ${step}: disagreed on ${JSON.stringify(text)}`,+ );+ }+ }+});diff --git a/studio/frontend/tests/trailing-placeholder-reseed.test.ts b/studio/frontend/tests/trailing-placeholder-reseed.test.tsnew file mode 100644index 00000000000..f268e1225c9--- /dev/null+++ b/studio/frontend/tests/trailing-placeholder-reseed.test.ts@@ -0,0 +1,175 @@+// 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 watch exists so the adapter can skip the strip on almost every arrival. That is only+// sound if the gate never closes on an arrival the strip WOULD have cut:+//+// isCandidate() is never false when stripTrailingTemplatePlaceholder would cut.+//+// If it is ever false at such a moment the reply keeps a `${...}` fragment that the previous+// build removed, which is a visible difference in the user's text rather than a slower path.+//+// The cases beside this one work on short buffers, where the reseed after a strip never comes+// under pressure: it deliberately looks back a bounded window and forgets everything older, so+// only a buffer longer than that window can catch it forgetting something it still needs. These+// cases cross that window repeatedly.++import assert from "node:assert/strict";+import test from "node:test";++import {+ TRAILING_PLACEHOLDER_WINDOW as W,+ createTrailingPlaceholderWatch,+ stripTrailingTemplatePlaceholder,+} from "../src/features/chat/utils/trailing-template-placeholder.ts";++type Watch = ReturnType<typeof createTrailingPlaceholderWatch>;++const failures: string[] = [];+let checks = 0;+let strips = 0;++function check(where: string, watch: Watch, text: string) {+ checks += 1;+ const stripped = stripTrailingTemplatePlaceholder(text);+ const wouldCut = stripped.length !== text.length;+ if (wouldCut && !watch.isCandidate()) {+ failures.push(+ `${where}: the strip would cut ${text.length - stripped.length} characters but ` ++ `isCandidate() said no. tail=${JSON.stringify(text.slice(-60))}`,+ );+ }+ return { stripped, wouldCut };+}++/** Drive the watch exactly as the adapter does, checking at every arrival. */+function drive(where: string, arrivals: string[], seedText = ""): void {+ const watch = createTrailingPlaceholderWatch();+ let text = seedText;+ if (text) watch.append(text);+ arrivals.forEach((arrival, index) => {+ if (!arrival) return;+ text += arrival;+ watch.append(arrival);+ const { stripped, wouldCut } = check(`${where}@${index}`, watch, text);+ if (watch.isCandidate() && wouldCut) {+ strips += 1;+ text = stripped;+ watch.retract(text);+ // A second fragment can be sitting at the end already, so the invariant has to+ // hold again immediately after the retract, not only after the next arrival.+ check(`${where}@${index}:after-retract`, watch, text);+ }+ });+}++const filler = (n: number, ch = "x") => ch.repeat(n);++test("the gate never closes on an arrival the strip would cut", () => {+ // Two fragments back to back: the first strip is followed by a second the reseed has to+ // rediscover from the buffer rather than from what it was tracking.+ for (const gap of [+ 0,+ 1,+ 5,+ 100,+ W - 10,+ W,+ W + 10,+ 2 * W - 10,+ 2 * W,+ 2 * W + 10,+ ]) {+ drive(`two fragments gap=${gap}`, [+ `start ${filler(gap)}\${first}`,+ "${second}",+ ]);+ }++ // A fragment, a strip, then only whitespace, so the next cut is of the fragment the+ // reseed had to remember across the strip.+ for (const gap of [+ 0,+ 10,+ W - 4,+ W,+ W + 4,+ 2 * W - 4,+ 2 * W,+ 2 * W + 4,+ 3 * W,+ ]) {+ drive(`fragment then whitespace gap=${gap}`, [+ `head ${filler(gap)}\${a}\${b}`,+ " ",+ "\n",+ " ",+ ]);+ }++ // The opener landing on each offset either side of the reseed edge.+ for (let back = 2 * W - 6; back <= 2 * W + 6; back += 1) {+ drive(`reseed edge back=${back}`, [+ `\${outer${filler(Math.max(0, back))}`,+ "}",+ "${inner}",+ " ",+ ]);+ }++ // A resumed turn: the buffer starts non-empty and the watch is caught up with one+ // append of the whole partial, which is what the adapter does.+ for (const gap of [0, W, 2 * W, 3 * W]) {+ drive("resumed", ["${b}", " "], `resumed ${filler(gap)}\${a}`);+ }++ assert.deepEqual(+ failures,+ [],+ `${failures.length} violations over ${checks} states`,+ );+ assert.ok(+ strips > 0,+ "no strip ever fired, so the invariant was never actually exercised",+ );+});++test("randomised streams far longer than the reseed window", () => {+ // Seeded, so a failure is reproducible from the name in the message.+ const makeRandom = (seed: number) => {+ let value = seed >>> 0;+ return () => {+ value = (value * 1664525 + 1013904223) >>> 0;+ return value / 0x100000000;+ };+ };+ const alphabet = [+ "a",+ " ",+ "\n",+ "$",+ "{",+ "}",+ "${",+ "}$",+ "${}",+ "x".repeat(50),+ "y".repeat(700),+ ];++ const before = failures.length;+ for (let seed = 1; seed <= 120; seed += 1) {+ const random = makeRandom(seed);+ const arrivals: string[] = [];+ for (let i = 0; i < 200; i += 1) {+ let piece = "";+ const n = 1 + Math.floor(random() * 3);+ for (let k = 0; k < n; k += 1) {+ piece += alphabet[Math.floor(random() * alphabet.length)];+ }+ arrivals.push(piece);+ }+ drive(`random seed=${seed}`, arrivals);+ }+ assert.deepEqual(failures.slice(before), []);+});diff --git a/studio/frontend/tests/trailing-placeholder-watch.test.ts b/studio/frontend/tests/trailing-placeholder-watch.test.tsnew file mode 100644index 00000000000..52764fd91eb--- /dev/null+++ b/studio/frontend/tests/trailing-placeholder-watch.test.ts@@ -0,0 +1,171 @@+// 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 {+ createTrailingPlaceholderWatch,+ stripTrailingTemplatePlaceholder,+} from "../src/features/chat/utils/trailing-template-placeholder.ts";++/**+ * The one property that matters: the watch never says no when the strip would+ * cut. Saying yes when it would not is allowed, and costs one scan.+ *+ * Everything else in the adapter is downstream of that, because the strip only+ * runs on an arrival the watch admits.+ */+function assertSound(text: string, candidate: boolean, label: string): void {+ const stripped = stripTrailingTemplatePlaceholder(text);+ if (stripped.length !== text.length) {+ assert.equal(+ candidate,+ true,+ `${label}: the strip cut ${JSON.stringify(text)} down to ${JSON.stringify(stripped)}, but the watch said there was nothing to do`,+ );+ }+}++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("the watch admits every fragment the strip would cut", () => {+ const alphabet = [+ "$",+ "{",+ "}",+ "${",+ "${x}",+ "a",+ " ",+ "\n",+ "x}",+ "${a",+ "b}c",+ "}}",+ "${}",+ ];+ const random = mulberry32(20260817);+ let cuts = 0;+ let admitted = 0;+ let states = 0;+ for (let seed = 0; seed < 2000; seed += 1) {+ const watch = createTrailingPlaceholderWatch();+ let text = "";+ for (let step = 0; step < 20; step += 1) {+ const delta = alphabet[random() % alphabet.length];+ text += delta;+ watch.append(delta);+ const candidate = watch.isCandidate();+ states += 1;+ if (candidate) admitted += 1;+ assertSound(text, candidate, `seed ${seed} step ${step}`);+ // What the adapter does with a yes: run the strip, and if it cut, tell+ // the watch what is left.+ if (candidate) {+ const stripped = stripTrailingTemplatePlaceholder(text);+ if (stripped.length !== text.length) {+ cuts += 1;+ text = stripped;+ watch.retract(text);+ }+ }+ }+ }+ assert.equal(cuts > 500, true, `only ${cuts} strips exercised`);+ assert.equal(states > 10_000, true, `only ${states} states exercised`);+ // The point of the watch is that most arrivals never reach the strip. If+ // this ever admitted everything it would be sound and useless.+ assert.equal(+ admitted < states / 2,+ true,+ `the watch admitted ${admitted} of ${states} states; it is not rejecting anything`,+ );+});++test("the watch admits every fragment the strip would cut, on prose", () => {+ // Brace-heavy prose, which is what a code fence looks like: plenty of lines+ // ending in `}` with no `${` in front of them.+ const lines = [+ "function step(input) {\n",+ " return { ...input };\n",+ "}\n",+ "\n",+ "text and more text ",+ "a `${x}` in a sentence ",+ "closing }\n",+ ];+ const random = mulberry32(7);+ let admitted = 0;+ let states = 0;+ for (let seed = 0; seed < 200; seed += 1) {+ const watch = createTrailingPlaceholderWatch();+ let text = "";+ for (let step = 0; step < 40; step += 1) {+ const piece = lines[random() % lines.length];+ // Split each piece into small arrivals, the way tokens land.+ for (let at = 0; at < piece.length; at += 3) {+ const delta = piece.slice(at, at + 3);+ text += delta;+ watch.append(delta);+ const candidate = watch.isCandidate();+ states += 1;+ if (candidate) admitted += 1;+ assertSound(text, candidate, `seed ${seed} step ${step}`);+ if (candidate) {+ const stripped = stripTrailingTemplatePlaceholder(text);+ if (stripped.length !== text.length) {+ text = stripped;+ watch.retract(text);+ }+ }+ }+ }+ }+ assert.equal(states > 10_000, true, `only ${states} states exercised`);+ assert.equal(+ admitted * 20 < states,+ true,+ `the watch admitted ${admitted} of ${states} prose states; a code fence must not keep waking the strip`,+ );+});++test("a fragment split across arrivals is still admitted", () => {+ for (const pieces of [+ ["a ", "$", "{", "x", "}"],+ ["a ", "${", "x}"],+ ["a ", "${x", "}"],+ ["a ", "${x}"],+ ["a ", "$", "{x}", " "],+ ]) {+ const watch = createTrailingPlaceholderWatch();+ let text = "";+ for (const piece of pieces) {+ text += piece;+ watch.append(piece);+ }+ assert.equal(+ watch.isCandidate(),+ true,+ `${JSON.stringify(pieces)} was not admitted, so the strip would never run on it`,+ );+ assert.equal(stripTrailingTemplatePlaceholder(text), "a");+ }+});++test("ordinary prose is rejected without the buffer being read", () => {+ const watch = createTrailingPlaceholderWatch();+ for (const delta of ["the answer", " is ", "forty two", ".\n\n", "done"]) {+ watch.append(delta);+ assert.equal(watch.isCandidate(), false);+ }+});