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: replace reasoning pagination with a continuous transcript (#11522)
Wasim Yousef Said5c63c8f67789
diff --git a/studio/frontend/smoke-reasoning-transcript-main.tsx b/studio/frontend/smoke-reasoning-transcript-main.tsxnew file mode 100644index 00000000000..91ec21bb46d--- /dev/null+++ b/studio/frontend/smoke-reasoning-transcript-main.tsx@@ -0,0 +1,209 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/* eslint-disable no-restricted-imports -- Match the app's entry order through the chat cycle. */+import "@/features/chat/stores/sidebar-organization-store";+import { useChatPreferencesStore } from "@/features/chat";+/* eslint-enable no-restricted-imports */+import { Thread } from "@/components/assistant-ui/thread";+import { TooltipProvider } from "@/components/ui/tooltip";+import {+ AssistantRuntimeProvider,+ ExportedMessageRepository,+ useAui,+ useLocalRuntime,+ type ChatModelAdapter,+} from "@assistant-ui/react";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { useEffect } from "react";+import { createRoot } from "react-dom/client";+import "./src/index.css";++// A real Thread/runtime, deterministic bytes, no backend, authentication, or model.+const fetchOriginal = window.fetch.bind(window);+window.fetch = (input, init) => {+ const url =+ typeof input === "string"+ ? input+ : input instanceof URL+ ? input.href+ : input.url;+ if (/\/api\/skills(?:\?|$)/.test(url))+ return Promise.resolve(Response.json({ skills: [] }));+ if (/\/api\/chat\/threads\/[^/]+\/forks$/.test(url))+ return Promise.resolve(Response.json({ counts: {} }));+ if (/\/api\/chat\/projects(?:\?|$)/.test(url))+ return Promise.resolve(Response.json({ projects: [] }));+ if (/\/api\/rag\/knowledge-bases(?:\?|$)/.test(url))+ return Promise.resolve(Response.json({ knowledge_bases: [] }));+ return fetchOriginal(input, init);+};+useChatPreferencesStore.setState({ thinkingVisibility: "expanded" });++type Options = {+ size?: number;+ kind?: "mixed" | "code" | "line";+ chunk?: number;+ gap?: number;+ userPrompt?: string;+ text?: string;+};+let source = "";+let config: Required<Options> = {+ size: 100000,+ kind: "mixed",+ chunk: 4096,+ gap: 16,+ userPrompt: "Create a Flappy Bird game in HTML.",+ text: "",+};+let started = 0;+let finished = 0;+let frames: number[] = [];++function fixture(size: number, kind: Options["kind"]): string {+ let text =+ "I’ll build a **Flappy Bird game** with a small canvas, simple physics, and keyboard controls.\n\n";+ if (kind === "code" || kind === "line") {+ text += "```javascript\n";+ let line = 0;+ while (text.length < size - 60) {+ text +=+ kind === "line"+ ? "constellation"+ : `const bird${line} = { x: 80, y: ${line++}, velocity: 0 };\n`;+ }+ text += "\n```\n\nThe code is ready. **REASONING_END**";+ return text;+ }+ let i = 0;+ while (text.length < size - 200) {+ text += `**Thought ${i++}.** The bird needs gravity and a gentle upward impulse. Keep the game loop independent of frame rate so it feels consistent.\n\n`;+ if (i % 6 === 0)+ text +=+ "```javascript\nconst dt = Math.min(elapsed / 1000, 0.05);\nbird.velocity += gravity * dt;\nbird.y += bird.velocity * dt;\n```\n\n";+ }+ return text + "**REASONING_END** — ready to write the answer.";+}++const adapter: ChatModelAdapter = {+ async *run({ abortSignal }) {+ started = performance.now();+ for (+ let end = config.chunk;+ end < source.length + config.chunk;+ end += config.chunk+ ) {+ if (abortSignal.aborted) return;+ yield { content: [{ type: "reasoning", text: source.slice(0, end) }] };+ await new Promise((resolve) => setTimeout(resolve, config.gap));+ }+ finished = performance.now();+ },+};++function Api() {+ const aui = useAui();+ useEffect(() => {+ let previous = 0;+ let frame = requestAnimationFrame(function sample(time) {+ if (started && !finished && previous >= started)+ frames.push(time - previous);+ previous = time;+ frame = requestAnimationFrame(sample);+ });+ const api = {+ run(options: Options = {}) {+ config = {+ size: 100000,+ kind: "mixed",+ chunk: 4096,+ gap: 16,+ userPrompt: "Create a Flappy Bird game in HTML.",+ text: "",+ ...options,+ };+ source = config.text || fixture(config.size, config.kind);+ started = 0;+ finished = 0;+ frames = [];+ aui.thread().import(ExportedMessageRepository.fromArray([]));+ aui.thread().append({+ role: "user",+ content: [{ type: "text", text: config.userPrompt }],+ });+ },+ seed(options: Options = {}) {+ source =+ options.text ??+ fixture(options.size ?? 100000, options.kind ?? "mixed");+ aui.thread().import(+ ExportedMessageRepository.fromArray([+ {+ id: "fixture-user",+ role: "user",+ content: [+ {+ type: "text",+ text:+ options.userPrompt ?? "Create a Flappy Bird game in HTML.",+ },+ ],+ },+ {+ id: "fixture-assistant",+ role: "assistant",+ content: [{ type: "reasoning", text: source }],+ },+ ]),+ );+ },+ source: () => source,+ stats: () => {+ const sorted = [...frames].sort((a, b) => a - b);+ return {+ done: finished > 0,+ duration: finished - started,+ p95: sorted[Math.floor(sorted.length * 0.95)] ?? 0,+ worst: sorted.at(-1) ?? 0,+ mounted:+ document.querySelector('[data-slot="reasoning-text"]')?.textContent+ ?.length ?? 0,+ fragments: document.querySelectorAll("[data-reasoning-fragment]")+ .length,+ };+ },+ };+ Object.assign(window, { __reasoning: api });+ return () => cancelAnimationFrame(frame);+ }, [aui]);+ return null;+}++function Harness() {+ const runtime = useLocalRuntime(adapter);+ return (+ <TooltipProvider>+ <AssistantRuntimeProvider runtime={runtime}>+ <Api />+ <div className="flex h-dvh flex-col">+ <Thread hideWelcome />+ </div>+ </AssistantRuntimeProvider>+ </TooltipProvider>+ );+}++const route = createRootRoute({ component: Harness });+const router = createRouter({+ routeTree: route,+ history: createMemoryHistory({ initialEntries: ["/"] }),+});+createRoot(document.getElementById("root")!).render(+ <RouterProvider router={router as never} />,+);diff --git a/studio/frontend/smoke-reasoning-transcript.html b/studio/frontend/smoke-reasoning-transcript.htmlnew file mode 100644index 00000000000..22cdcd270ca--- /dev/null+++ b/studio/frontend/smoke-reasoning-transcript.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <script src="/crypto-boot.js"></script>+ <title>Reasoning transcript smoke</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/smoke-reasoning-transcript-main.tsx"></script>+ </body>+</html>diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsxindex 094f4f3d860..6731d6f73f3 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx@@ -686,23 +686,29 @@ const tokenStyle = (* moves far enough for the window to move. A fence growing by a character re-renders its last line* and nothing else.*/-const FenceLine = memo(function FenceLine({+export const FenceLine = memo(function FenceLine({line,windowed,+ inline = false,}: {line: TokenLine;windowed: boolean;+ inline?: boolean;}) {- if (isBlankLine(line)) {+ if (!inline && isBlankLine(line)) {return <span className={LINE_CLASS}>{"\n"}</span>;}if (!windowed) {// One text node for the whole line. Same characters, same block box, same height: the only// thing this line has given up is its colour, and it is off screen.- return <span className={LINE_CLASS}>{plainLineText(line)}</span>;+ return (+ <span className={inline ? "inline" : LINE_CLASS}>+ {plainLineText(line)}+ </span>+ );}return (- <span className={LINE_CLASS}>+ <span className={inline ? "inline" : LINE_CLASS}>{line.map((token, index) => {const { style, hasBackground } = tokenStyle(token);return (diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex 04651964f50..123a58c9ce1 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -496,7 +496,7 @@ function MermaidCopyButton({ source }: { source: string }) {);}-function CodeBlockActions({+export function CodeBlockActions({disabled,language,source,@@ -1228,7 +1228,7 @@ const MarkdownTextSourceImpl = ({);export const MarkdownText = withSmoothContextProvider(MarkdownTextImpl);-// Reasoning pages render at message-group scope, where assistant-ui deliberately+// Reasoning fragments render at message-group scope, where assistant-ui deliberately// exposes no `part`. Its smooth wrapper reads that property, so the source-fed// renderer must stay independent of both the part adapter and that wrapper.export const MarkdownTextSource = MarkdownTextSourceImpl;diff --git a/studio/frontend/src/components/assistant-ui/reasoning-code-index.ts b/studio/frontend/src/components/assistant-ui/reasoning-code-index.tsnew file mode 100644index 00000000000..1adb749c961--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/reasoning-code-index.ts@@ -0,0 +1,153 @@+// 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 {+ ReasoningCodeLine,+ ReasoningFragment,+} from "./reasoning-transcript-index.ts";++const CHARACTERS = 8192;+const LINES = 16;+type Options = {+ bodyStart: number;+ indent: number;+ language: string | null;+ key: string;+ document: number;+ start: number;+};++/** Retain completed rows; only the bounded, unfinished row is revisited on append. */+export class ReasoningCodeIndex {+ private rows: ReasoningFragment[] = [];+ private cursor: number;+ private line = 0;+ private column = 0;+ private committedSource = "";+ private context = { source: "", incomplete: true };+ private options: Options;+ private previousText = "";+ private previousEnd = -1;+ private result: ReasoningFragment[] = [];++ constructor(options: Options) {+ this.options = options;+ this.cursor = options.bodyStart;+ }++ update(text: string, bodyEnd: number, incomplete: boolean): ReasoningFragment[] {+ this.context.incomplete = incomplete;+ if (text === this.previousText && bodyEnd === this.previousEnd)+ return this.result;+ this.previousText = text;+ this.previousEnd = bodyEnd;+ // A fence's terminal newline is not an extra blank code line. It becomes+ // interior on the next append and is then consumed by the pending row.+ let end = bodyEnd;+ let trailingIndent = 0;+ while (+ trailingIndent < this.options.indent &&+ text[end - trailingIndent - 1] === " "+ )+ trailingIndent += 1;+ if (text[end - trailingIndent - 1] === "\n") end -= trailingIndent;+ if (text[end - 1] === "\n") end -= text[end - 2] === "\r" ? 2 : 1;+ else if (text[end - 1] === "\r") end -= 1;+ const result = [...this.rows];+ let cursor = this.cursor;+ let line = this.line;+ let column = this.column;+ let group: ReasoningCodeLine[] = [];+ let characters = 0;+ let pendingSource = "";+ const flush = (commit: boolean) => {+ if (!group.length) return;+ const first = group[0];+ const context = this.context;+ const row: ReasoningFragment = {+ key: `${this.options.key}:code:${first.line}:${first.column}`,+ document: this.options.document,+ start: this.options.start,+ end: this.options.start + cursor,+ text: group.map((part) => part.text).join("\n"),+ first: result.length === 0,+ last: !commit,+ code: {+ get source() {+ return context.source;+ },+ get incomplete() {+ return context.incomplete;+ },+ language: this.options.language,+ lines: group,+ },+ };+ result.push(row);+ if (commit) {+ this.rows.push(row);+ this.cursor = cursor;+ this.line = line;+ this.column = column;+ this.committedSource += pendingSource;+ pendingSource = "";+ }+ group = [];+ characters = 0;+ };+ while (cursor < end) {+ const newline = text.indexOf("\n", cursor);+ const rawEnd = newline < 0 || newline >= end ? end : newline;+ const lineEnd =+ text[rawEnd - 1] === "\r" && newline === rawEnd ? rawEnd - 1 : rawEnd;+ let from = cursor;+ let carry = "";+ if (column === 0) {+ let indentation = 0;+ while (indentation < this.options.indent && from < lineEnd) {+ if (text[from] === " ") indentation += 1;+ else if (text[from] === "\t") indentation += 4 - (indentation % 4);+ else break;+ from += 1;+ }+ carry = " ".repeat(Math.max(0, indentation - this.options.indent));+ }+ const budget = CHARACTERS - characters - carry.length;+ let stop = Math.min(lineEnd, from + budget);+ if (stop < lineEnd && /[\uD800-\uDBFF]/.test(text[stop - 1])) stop -= 1;+ if (stop <= from && from < lineEnd) {+ flush(true);+ continue;+ }+ const part = carry + text.slice(from, stop);+ group.push({ line, column, text: part });+ characters += part.length;+ pendingSource += part;+ if (stop === lineEnd && rawEnd < end) {+ cursor = rawEnd + 1;+ line += 1;+ column = 0;+ pendingSource += "\n";+ characters += 1;+ } else {+ cursor = stop === lineEnd ? rawEnd : stop;+ column += part.length;+ }+ if (+ cursor < end &&+ (characters >= CHARACTERS - 1 || group.length >= LINES)+ )+ flush(true);+ }+ if (!group.length && result.length === 0)+ group.push({ line: 0, column: 0, text: "" });+ flush(false);+ this.context.source = this.committedSource + pendingSource;+ if (cursor > end)+ this.context.source = this.context.source.replace(/\n$/, "");+ if (result.length && !result.at(-1)!.last)+ result[result.length - 1] = { ...result.at(-1)!, last: true };+ this.result = result;+ return result;+ }+}diff --git a/studio/frontend/src/components/assistant-ui/reasoning-highlight.ts b/studio/frontend/src/components/assistant-ui/reasoning-highlight.tsnew file mode 100644index 00000000000..c932d223d32--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/reasoning-highlight.ts@@ -0,0 +1,44 @@+// 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 { HighlightResult } from "@streamdown/code";++export type ReasoningHighlightRequest = {+ client: number;+ revision: number;+ source: string | { from: number; text: string };+ language: string | null;+ lines: number[];+};++/** A client sends its complete source once, then only newly appended bytes. */+export function reasoningHighlightSource(+ previous: string,+ source: ReasoningHighlightRequest["source"],+): string {+ return typeof source === "string"+ ? source+ : previous.slice(0, source.from) + source.text;+}+export type ReasoningHighlightReply = {+ client: number;+ revision: number;+ lines: { line: number; tokens: HighlightResult["tokens"][number] }[];+};++/** Transfer only requested lines; the worker keeps the complete grammar context. */+export function reasoningHighlightReply(+ request: ReasoningHighlightRequest,+ result: HighlightResult | null,+): ReasoningHighlightReply {+ return {+ client: request.client,+ revision: request.revision,+ lines: result+ ? request.lines.flatMap((line) => {+ const tokens = result.tokens[line];+ return tokens ? [{ line, tokens }] : [];+ })+ : [],+ };+}diff --git a/studio/frontend/src/components/assistant-ui/reasoning-highlight.worker.ts b/studio/frontend/src/components/assistant-ui/reasoning-highlight.worker.tsnew file mode 100644index 00000000000..3c97b2fc47b--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/reasoning-highlight.worker.ts@@ -0,0 +1,64 @@+// 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 { createCodePlugin, normalizeLanguage } from "./code-plugin";+import { unslothDarkTheme, unslothLightTheme } from "./code-themes";+import {+ reasoningHighlightReply,+ reasoningHighlightSource,+ type ReasoningHighlightRequest,+} from "./reasoning-highlight";++const themes = [unslothLightTheme, unslothDarkTheme] as const;+const highlighter = createCodePlugin({ themes: [...themes] });+const pending = new Map<number, ReasoningHighlightRequest>();+const revisions = new Map<number, number>();+const sources = new Map<number, string>();+let scheduled = false;++self.onmessage = ({+ data,+}: MessageEvent<ReasoningHighlightRequest | { cancel: number }>) => {+ if ("cancel" in data) {+ pending.delete(data.cancel);+ revisions.delete(data.cancel);+ sources.delete(data.cancel);+ return;+ }+ const source = reasoningHighlightSource(+ sources.get(data.client) ?? "",+ data.source,+ );+ sources.set(data.client, source);+ pending.set(data.client, { ...data, source });+ revisions.set(data.client, data.revision);+ if (scheduled) return;+ scheduled = true;+ // If tokenization was busy, queued appends coalesce before the next pass.+ setTimeout(() => {+ scheduled = false;+ const requests = [...pending.values()];+ pending.clear();+ for (const request of requests) {+ const publish = (+ result: Parameters<typeof reasoningHighlightReply>[1],+ ) => {+ if (revisions.get(request.client) === request.revision)+ self.postMessage(reasoningHighlightReply(request, result));+ };+ try {+ const result = highlighter.highlight(+ {+ code: request.source as string,+ language: normalizeLanguage(request.language ?? "text"),+ themes: [...themes],+ },+ publish,+ );+ publish(result);+ } catch {+ publish(null);+ }+ }+ }, 0);+};diff --git a/studio/frontend/src/components/assistant-ui/reasoning-pagination.ts b/studio/frontend/src/components/assistant-ui/reasoning-pagination.tsdeleted file mode 100644index eb4972eed23..00000000000--- a/studio/frontend/src/components/assistant-ui/reasoning-pagination.ts+++ /dev/null@@ -1,377 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--// Short traces keep the existing renderer and DOM. Once pagination starts, only-// one page is mounted and each page stays small enough for responsive selection-// and browser find.-export const REASONING_PAGINATION_THRESHOLD = 16_384;-export const REASONING_PAGE_CHARACTERS = 8_192;--const BOUNDARY_SEARCH_CHARACTERS = 1_024;-const BOUNDARY_CONTEXT_CHARACTERS = 128;-const FENCE_LINE_RE = /^( {0,3})(`{3,}|~{3,})(.*)\r?$/;--const HIGH_SURROGATE_RE = /[\uD800-\uDBFF]/;-const LOW_SURROGATE_RE = /[\uDC00-\uDFFF]/;--type FenceRange = {- end: number;- start: number;-};--export type ReasoningPage = {- end: number;- hasEarlier: boolean;- hasNewer: boolean;- markdown: string;- oversizedCode: boolean;- start: number;-};--type ReasoningPageOptions = {- end?: number | null;- maxCharacters?: number;- streaming?: boolean;-};--export type ReasoningPageBoundary = {- after: string;- before: string;- end: number;-};--export function shouldPaginateReasoning(markdown: string): boolean {- return markdown.length > REASONING_PAGINATION_THRESHOLD;-}--export function createReasoningPageBoundary(- markdown: string,- end: number,-): ReasoningPageBoundary {- const boundedEnd = Math.max(0, Math.min(markdown.length, Math.floor(end)));- return {- after: markdown.slice(boundedEnd, boundedEnd + BOUNDARY_CONTEXT_CHARACTERS),- before: markdown.slice(- Math.max(0, boundedEnd - BOUNDARY_CONTEXT_CHARACTERS),- boundedEnd,- ),- end: boundedEnd,- };-}--export function isReasoningPageBoundaryValid(- markdown: string,- boundary: ReasoningPageBoundary,-): boolean {- return (- boundary.end <= markdown.length &&- markdown.slice(boundary.end, boundary.end + boundary.after.length) ===- boundary.after &&- markdown.slice(boundary.end - boundary.before.length, boundary.end) ===- boundary.before- );-}--type OpenFence = {- character: string;- length: number;- start: number;-};--function consumeFenceLine(- line: string,- lineStart: number,- lineEnd: number,- open: OpenFence | null,-): { closed?: FenceRange; open: OpenFence | null } {- const match = line.match(FENCE_LINE_RE);- if (!match) {- return { open };- }- const marker = match[2];- if (- open &&- marker[0] === open.character &&- marker.length >= open.length &&- match[3].trim().length === 0- ) {- return {- closed: { start: open.start, end: lineEnd },- open: null,- };- }- if (open) {- return { open };- }- return {- open: {- character: marker[0],- length: marker.length,- start: lineStart,- },- };-}--// Streaming appends should not rescan a million-character trace just to choose-// its last 8 KiB. Only complete newly appended lines advance this scanner; a-// partial trailing line is reconsidered when its newline arrives.-export class ReasoningPageSelector {- private committedOffset = 0;- private documentIndex = -1;-- // Each reasoning part is an independent Markdown document, even when adjacent.- selectDocument(- documents: readonly string[],- options: ReasoningPageOptions = {},- ): ReasoningPage & { documentIndex: number } {- const total = documents.reduce((length, text) => length + text.length, 0);- const end = Math.max(0, Math.min(total, options.end ?? total));- let offset = 0;- let index = 0;- while (- index < documents.length - 1 &&- offset + documents[index].length < end- ) {- offset += documents[index].length;- index += 1;- }- if (index !== this.documentIndex) {- this.reset();- this.source = "";- this.documentIndex = index;- }- const page = this.select(documents[index] ?? "", {- ...options,- end: end - offset,- });- return {- ...page,- documentIndex: index,- start: offset + page.start,- end: offset + page.end,- hasEarlier: offset + page.start > 0,- hasNewer: offset + page.end < total,- };- }-- private liveStart: number | null = null;- private open: OpenFence | null = null;- private ranges: FenceRange[] = [];- private source = "";-- private reset(): void {- this.committedOffset = 0;-- this.liveStart = null;- this.open = null;- this.ranges = [];- }-- private update(markdown: string): readonly FenceRange[] {- const previousLength = this.source.length;- const comparisonStart = Math.max(- 0,- previousLength - BOUNDARY_CONTEXT_CHARACTERS,- );- const extendsSource =- markdown === this.source ||- (markdown.length > previousLength &&- markdown.slice(- 0,- Math.min(previousLength, BOUNDARY_CONTEXT_CHARACTERS),- ) === this.source.slice(0, BOUNDARY_CONTEXT_CHARACTERS) &&- markdown.slice(comparisonStart, previousLength) ===- this.source.slice(comparisonStart));- if (!extendsSource) {- this.reset();- }- this.source = markdown;-- // A giant unbroken streaming line has no fence state to advance. Search- // only the appended suffix until a newline finally completes that line.- if (- extendsSource &&- this.committedOffset < previousLength &&- markdown.indexOf("\n", previousLength) < 0- ) {- return this.open- ? [...this.ranges, { start: this.open.start, end: markdown.length }]- : this.ranges;- }-- while (this.committedOffset < markdown.length) {- const newline = markdown.indexOf("\n", this.committedOffset);- if (newline < 0) {- break;- }- const result = consumeFenceLine(- markdown.slice(this.committedOffset, newline),- this.committedOffset,- newline + 1,- this.open,- );- this.open = result.open;- if (result.closed) {- this.ranges.push(result.closed);- }- this.committedOffset = newline + 1;- }-- return this.open- ? [...this.ranges, { start: this.open.start, end: markdown.length }]- : this.ranges;- }-- select(markdown: string, options: ReasoningPageOptions = {}): ReasoningPage {- const fences = this.update(markdown);- const page = selectReasoningPageWithFences(markdown, options, fences);- if (!options.streaming) {- return page;- }-- const maxCharacters = Math.max(- 1,- Math.floor(options.maxCharacters ?? REASONING_PAGE_CHARACTERS),- );- if (this.liveStart === null || this.liveStart > page.end) {- this.liveStart = page.start;- }- const stride = Math.max(1, Math.floor(maxCharacters / 2));- while (page.end - this.liveStart > maxCharacters) {- // Advance by half a page. The overlap keeps context on screen and means- // ordinary token appends do not replace/reparse the full 8 KiB page.- this.liveStart = pageStart(- markdown,- this.liveStart + stride + maxCharacters,- maxCharacters,- fences,- );- }- return reasoningPageFromBounds(markdown, this.liveStart, page.end, fences);- }-- selectRanges(markdown: string): readonly FenceRange[] {- return this.update(markdown);- }-}--function fencedRanges(markdown: string): readonly FenceRange[] {- return new ReasoningPageSelector().selectRanges(markdown);-}--function isInsideFence(offset: number, fences: readonly FenceRange[]): boolean {- return fences.some((fence) => offset > fence.start && offset < fence.end);-}--function avoidBrokenSurrogate(markdown: string, offset: number): number {- if (- offset > 0 &&- offset < markdown.length &&- HIGH_SURROGATE_RE.test(markdown[offset - 1]) &&- LOW_SURROGATE_RE.test(markdown[offset])- ) {- return offset + 1;- }- return offset;-}--function pageStart(- markdown: string,- end: number,- maxCharacters: number,- fences: readonly FenceRange[],-): number {- const target = Math.max(0, end - maxCharacters);- if (target === 0) {- return 0;- }- const searchEnd = Math.min(end, target + BOUNDARY_SEARCH_CHARACTERS);-- // Prefer a paragraph boundary, then any complete line. Starting after the- // newline preserves CRLF and avoids changing the previous page's bytes.- for (const separator of ["\n\n", "\n"] as const) {- let cursor = target;- while (cursor < searchEnd) {- const found = markdown.indexOf(separator, cursor);- if (found < 0 || found >= searchEnd) {- break;- }- const candidate = found + separator.length;- // A START MUST STAY STRICTLY BELOW `end`, so that every page holds at- // least one character. `Earlier` sets the next page's end to this start- // (reasoning.tsx, showEarlierPage), so a start that reaches `end` yields- // an empty page whose own start is the same offset again: the chain stops- // advancing and every character before it becomes unreachable by paging.- // `indexOf` only moves forward, so once one candidate is too far they all- // are. Reachable when `maxCharacters <= BOUNDARY_SEARCH_CHARACTERS`,- // which lets `searchEnd` reach `end` and a separator land just under it.- if (candidate >= end) {- break;- }- if (!isInsideFence(candidate, fences)) {- return candidate;- }- cursor = candidate;- }- }-- const start = avoidBrokenSurrogate(markdown, target);- if (start < end) {- return start;- }- // `maxCharacters` smaller than a surrogate pair. `avoidBrokenSurrogate` moved- // forward off a low half and landed on `end`; `target` is the high half, so- // stepping back one keeps the character whole rather than emitting an empty- // page or a page that opens on a lone low surrogate.- return Math.max(0, target - 1);-}--function selectReasoningPageWithFences(- markdown: string,- options: ReasoningPageOptions,- fences: readonly FenceRange[],-): ReasoningPage {- const maxCharacters = Math.max(- 1,- Math.floor(options.maxCharacters ?? REASONING_PAGE_CHARACTERS),- );- const end = Math.max(- 0,- Math.min(markdown.length, Math.floor(options.end ?? markdown.length)),- );- const start = pageStart(markdown, end, maxCharacters, fences);- return reasoningPageFromBounds(markdown, start, end, fences);-}--function reasoningPageFromBounds(- markdown: string,- start: number,- end: number,- fences: readonly FenceRange[],-): ReasoningPage {- const oversizedCode = fences.some(- (fence) =>- (start > fence.start && start < fence.end) ||- (end > fence.start && end < fence.end),- );-- return {- end,- hasEarlier: start > 0,- hasNewer: end < markdown.length,- markdown: markdown.slice(start, end),- oversizedCode,- start,- };-}--export function selectReasoningPage(- markdown: string,- options: ReasoningPageOptions = {},-): ReasoningPage {- return selectReasoningPageWithFences(- markdown,- options,- fencedRanges(markdown),- );-}diff --git a/studio/frontend/src/components/assistant-ui/reasoning-reading-anchor.ts b/studio/frontend/src/components/assistant-ui/reasoning-reading-anchor.tsnew file mode 100644index 00000000000..1cbd4cc0e2f--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/reasoning-reading-anchor.ts@@ -0,0 +1,93 @@+// 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 { ReasoningReadingAnchor } from "./reasoning-transcript-index.ts";++const passages = "p, pre, li, h1, h2, h3, h4, h5, h6, td, th";++function textNodes(root: Element): Text[] {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const nodes: Text[] = [];+ for (let node = walker.nextNode(); node; node = walker.nextNode())+ if (node.textContent && node.parentElement?.closest(passages))+ nodes.push(node as Text);+ return nodes;+}++/** Locate a text range without changing the user's native selection. */+export function reasoningTextRange(+ root: Element,+ text: string,+ occurrence = 0,+): Range | null {+ const nodes = textNodes(root);+ const source = nodes.map((node) => node.data).join("");+ let start = -1;+ for (let i = 0; i <= occurrence; i += 1) {+ start = source.indexOf(text, start + 1);+ if (start < 0) return null;+ }+ const range = document.createRange();+ let offset = 0;+ let started = false;+ for (const node of nodes) {+ if (!started && start < offset + node.length) {+ range.setStart(node, start - offset);+ started = true;+ }+ if (started && start + text.length <= offset + node.length) {+ range.setEnd(node, start + text.length - offset);+ return range;+ }+ offset += node.length;+ }+ return null;+}++/** Capture the first visible character, including when its block starts above the viewport. */+export function captureReasoningAnchor(+ root: Element,+ viewport: Element,+): ReasoningReadingAnchor | undefined {+ const bounds = viewport.getBoundingClientRect();+ const nodes = textNodes(root);+ let preceding = "";+ for (const node of nodes) {+ const range = document.createRange();+ range.selectNodeContents(node);+ const rect = range.getBoundingClientRect();+ if (+ rect.bottom <= bounds.top + 2 ||+ rect.top >= bounds.bottom ||+ !rect.width+ ) {+ preceding += node.data;+ continue;+ }+ let low = 0;+ let high = node.length - 1;+ while (low < high) {+ const middle = (low + high) >>> 1;+ range.setStart(node, middle);+ range.setEnd(node, middle + 1);+ if (range.getBoundingClientRect().bottom <= bounds.top + 2)+ low = middle + 1;+ else high = middle;+ }+ // Stay inside this text node so formatting and fragment boundaries cannot+ // make the anchor needle depend on synthesized layout whitespace.+ const text = node.data.slice(low, Math.min(node.length, low + 32));+ range.setStart(node, low);+ range.setEnd(node, low + text.length);+ const prefix = preceding + node.data.slice(0, low);+ let occurrence = 0;+ for (+ let at = prefix.indexOf(text);+ at >= 0;+ at = prefix.indexOf(text, at + 1)+ )+ occurrence += 1;+ return { text, top: range.getBoundingClientRect().top, occurrence };+ }+ return undefined;+}diff --git a/studio/frontend/src/components/assistant-ui/reasoning-transcript-index.ts b/studio/frontend/src/components/assistant-ui/reasoning-transcript-index.tsnew file mode 100644index 00000000000..cfeeb9da66d--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/reasoning-transcript-index.ts@@ -0,0 +1,600 @@+// 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 { fromMarkdown } from "mdast-util-from-markdown";+import { gfmFromMarkdown } from "mdast-util-gfm";+import { mathFromMarkdown } from "mdast-util-math";+import { gfm } from "micromark-extension-gfm";+import { math } from "micromark-extension-math";+import remend from "remend";+import type { Definition, RootContent } from "mdast";+import { markdownBlockFallback } from "./markdown-block-fallback.ts";+import { ReasoningCodeIndex } from "./reasoning-code-index.ts";++export const REASONING_TRANSCRIPT_THRESHOLD = 16_384;+export const REASONING_FRAGMENT_CHARACTERS = 8_192;++export type ReasoningCodeLine = { line: number; column: number; text: string };+export type ReasoningReadingAnchor = {+ text: string;+ top: number;+ occurrence?: number;+};+export type ReasoningFragment = {+ key: string;+ document: number;+ start: number;+ end: number;+ text: string;+ renderText?: string;+ /** Synthetic list containers continue an item without repeating its marker. */+ listContinuationDepth?: number;+ tableContinuation?: boolean;+ hidden?: boolean;+ /** Continuations have no paragraph gap or repeated code header. */+ first: boolean;+ last: boolean;+ code?: {+ source: string;+ incomplete: boolean;+ language: string | null;+ lines: readonly ReasoningCodeLine[];+ };+};++type Block = {+ start: number;+ end: number;+ text: string;+ continued: boolean;+ prefix?: string;+ listContinuationDepth?: number;+ tableContinuation?: boolean;+ hidden?: boolean;+ fence?: {+ bodyStart: number;+ bodyEnd: number;+ incomplete: boolean;+ indent: number;+ language: string | null;+ index?: ReasoningCodeIndex;+ };+};+type Fence = {+ marker: string;+ scan: number;+ bodyStart: number;+ closeStart?: number;+ block?: Block;+};++type MarkdownNode = {+ type: string;+ value?: string;+ position?: { start: { offset?: number }; end: { offset?: number } };+ children?: MarkdownNode[];+};++/** Used once at the short-to-windowed transition, not on streaming updates. */+export function findReasoningAnchor(+ fragments: readonly ReasoningFragment[],+ text: string,+ occurrence = 0,+): number {+ return resolveReasoningAnchor(fragments, { text, top: 0, occurrence }).index;+}++export function resolveReasoningAnchor(+ fragments: readonly ReasoningFragment[],+ anchor: ReasoningReadingAnchor,+): ReasoningReadingAnchor & { index: number } {+ const { text, occurrence = 0 } = anchor;+ const plain = (node: MarkdownNode): string =>+ node.value ?? node.children?.map(plain).join("") ?? "";+ const texts = fragments.map((fragment) =>+ fragment.code+ ? fragment.text+ : plain(fromMarkdown(fragment.renderText ?? fragment.text)),+ );+ const source = texts.join("");+ let start = -1;+ for (let i = 0; i <= occurrence; i += 1) {+ start = source.indexOf(text, start + 1);+ if (start < 0) return { ...anchor, index: -1 };+ }+ let offset = 0;+ for (const [index, part] of texts.entries()) {+ if (offset + part.length > start) {+ const local = start - offset;+ const needle = part.slice(+ local,+ Math.min(part.length, local + text.length),+ );+ let repeated = 0;+ for (+ let at = part.indexOf(needle);+ at >= 0 && at < local;+ at = part.indexOf(needle, at + 1)+ )+ repeated += 1;+ return { ...anchor, text: needle, occurrence: repeated, index };+ }+ offset += part.length;+ }+ return { ...anchor, index: -1 };+}++// Context is render-only: copy/export always use the original document. A long+// paragraph can cross a bold/code span; a quoted or nested fence can cross many+// fragments. Reopen only the construct at the split, never an unrelated block.+function continuationPrefix(+ text: string,+ nodes: readonly MarkdownNode[],+ cut: number,+): { prefix: string; listDepth: number; table?: boolean } {+ const atCut = (siblings: readonly MarkdownNode[]) => {+ if (siblings.some((node) => node.position?.start.offset === cut))+ return undefined;+ return siblings.find(+ (node, i) =>+ (node.position?.start.offset ?? 0) < cut &&+ ((node.position?.end.offset ?? 0) >= cut ||+ (i === siblings.length - 1 &&+ (node.type === "code" || node.type === "blockquote") &&+ !text.slice(node.position?.end.offset, cut).trim())),+ );+ };+ let last = atCut(nodes);+ const table = last?.type === "table" ? last : undefined;+ if (table) {+ const start = table.position?.start.offset ?? 0;+ const headerEnd = text.indexOf("\n", start);+ const delimiterEnd = text.indexOf("\n", headerEnd + 1);+ if (headerEnd >= 0 && delimiterEnd >= 0)+ return {+ prefix: text.slice(start, delimiterEnd + 1),+ listDepth: 0,+ table: true,+ };+ }+ const containers: { marker: string; list: boolean }[] = [];+ while (last) {+ if (last.type === "listItem") {+ const start = last.position?.start.offset ?? 0;+ const marker = /^ {0,3}(?:[-+*]|\d+[.)])[\t ]+/.exec(text.slice(start));+ if (marker) containers.push({ marker: marker[0], list: true });+ }+ if (last.type === "blockquote")+ containers.push({ marker: "> ", list: false });+ const child = last.children && atCut(last.children);+ if (!child) break;+ last = child;+ }+ let indent = "";+ let listPrefix = "";+ for (const [i, { marker, list }] of containers.entries()) {+ listPrefix += marker;+ indent += list ? " ".repeat(marker.length) : marker;+ if (+ list &&+ (containers.slice(i + 1).some((item) => item.list) ||+ last?.type === "list")+ )+ listPrefix += "\n" + indent;+ }+ if (last?.type === "code") {+ const start = last.position?.start.offset ?? 0;+ const lineStart = text.lastIndexOf("\n", start - 1) + 1;+ const lineEnd = text.indexOf("\n", start);+ const opener = text.slice(lineStart, lineEnd < 0 ? text.length : lineEnd);+ const match = /^([\t >]*(?:[-+*] |\d+[.)] )?)(`{3,}|~{3,})([^\n]*)$/.exec(+ opener,+ );+ const close = /^[\t >]*(`{3,}|~{3,})[\t ]*$/.exec(+ text.slice(0, cut).trimEnd().split("\n").at(-1) ?? "",+ );+ if (+ match &&+ !(+ close &&+ close[1][0] === match[2][0] &&+ close[1].length >= match[2].length+ )+ )+ return { prefix: `${opener}\n`, listDepth: 0 };+ }+ const trimmed = text.slice(0, cut).trimEnd();+ const repaired = remend(trimmed);+ const suffix = repaired.startsWith(trimmed)+ ? repaired.slice(trimmed.length)+ : "";+ const inlinePrefix =+ suffix && /^[*_`]+$/.test(suffix) ? [...suffix].reverse().join("") : "";+ return {+ prefix: listPrefix + inlinePrefix,+ listDepth: containers.filter((item) => item.list).length,+ };+}++function* referenceDefinitions(+ nodes: readonly RootContent[],+): Generator<Definition> {+ for (const node of nodes) {+ if (node.type === "definition") yield node;+ else if ("children" in node) yield* referenceDefinitions(node.children);+ }+}++function definitionSource(node: Definition): string {+ // Serialize without the quote/list container: definitions are document-scoped.+ const escape = (value: string) =>+ value.replace(/&/g, "&").replace(/[\\"]/g, "\\$&");+ const url = escape(+ node.url.replace(/[<>\s]/g, (character) => encodeURIComponent(character)),+ );+ const title = node.title == null ? "" : ` "${escape(node.title)}"`;+ return `[${node.label ?? node.identifier}]: <${url}>${title}`;+}++const normalizeReference = (label: string): string =>+ label+ .replace(/[\t\n\r ]+/g, " ")+ .trim()+ .toLowerCase()+ .toUpperCase();++function fenceAt(source: string, start: number): Fence | null {+ const newline = source.indexOf("\n", start);+ if (newline < 0) return null;+ const match = /^( {0,3})(`{3,}|~{3,})([^\n]*)$/.exec(+ source.slice(start, newline),+ );+ if (!match || (match[2][0] === "`" && match[3].includes("`"))) return null;+ return { marker: match[2], scan: newline + 1, bodyStart: newline + 1 };+}++/** Returns the end of a complete closing line. Only newly appended lines are scanned. */+function fenceEnd(source: string, fence: Fence): number | null {+ fence.closeStart = undefined;+ for (let from = fence.scan; from < source.length; ) {+ const newline = source.indexOf("\n", from);+ const end = newline < 0 ? source.length : newline;+ const line = source.slice(from, end);+ const match = /^ {0,3}(`{3,}|~{3,})[\t ]*\r?$/.exec(line);+ if (+ match &&+ match[1][0] === fence.marker[0] &&+ match[1].length >= fence.marker.length+ ) {+ // A partial closing line can acquire non-whitespace on the next append.+ fence.closeStart = from;+ return newline < 0 ? null : newline + 1;+ }+ if (newline < 0) break;+ from = newline + 1;+ fence.scan = from;+ }+ return null;+}++/** A UTF-16 boundary which cannot bisect CRLF or an astral character. */+export function reasoningFragmentEnd(+ text: string,+ start: number,+ budget: number,+): number {+ let end = Math.min(text.length, start + budget);+ if (+ end < text.length &&+ (/[\uD800-\uDBFF]/.test(text[end - 1]) ||+ (text[end - 1] === "\r" && text[end] === "\n"))+ )+ end -= 1;+ return Math.max(start + 1, end);+}++// Parse a bounded unfinished tail, retaining complete blocks. In particular, an open+// fence bypasses Markdown parsing after its opener: appending a token to a 250K fence+// must not ask a Markdown parser to read those 250K characters again.+class DocumentIndex {+ source = "";+ blocks: Block[] = [];+ private committed: Block[] = [];+ private offset = 0;+ private fence: Fence | null = null;+ private continued = false;+ private prefix = "";+ private listContinuationDepth = 0;+ private tableContinuation = false;+ definitions = new Map<string, { start: number; source: string }>();+ definitionsRevision = 0;+ generation = 0;++ update(source: string): void {+ if (source === this.source) return;+ if (!source.startsWith(this.source)) {+ this.committed = [];+ this.offset = 0;+ this.fence = null;+ this.continued = false;+ this.prefix = "";+ this.listContinuationDepth = 0;+ this.tableContinuation = false;+ this.definitions.clear();+ this.definitionsRevision += 1;+ this.generation += 1;+ }+ // Only the unfinished tail can change a previously seen definition.+ const previousDefinitions = new Map(this.definitions);+ for (const [key, definition] of this.definitions) {+ if (definition.start >= this.offset) this.definitions.delete(key);+ }+ this.source = source;+ const pending: Block[] = [];+ while (this.offset < source.length) {+ if (!this.prefix) this.fence ??= fenceAt(source, this.offset);+ if (this.fence) {+ const end = fenceEnd(source, this.fence);+ const block = (this.fence.block ??= {+ start: this.offset,+ end: end ?? source.length,+ text: source.slice(this.offset, end ?? source.length),+ continued: false,+ fence: {+ bodyStart: this.fence.bodyStart - this.offset,+ bodyEnd: 0,+ incomplete: true,+ indent: /^ */.exec(source.slice(this.offset))![0].length,+ language: markdownBlockFallback(+ source.slice(this.offset, this.fence.bodyStart),+ ).language,+ },+ });+ block.end = end ?? source.length;+ block.text = source.slice(this.offset, block.end);+ block.fence!.bodyEnd =+ (this.fence.closeStart ?? block.end) - this.offset;+ block.fence!.incomplete = this.fence.closeStart === undefined;+ if (end === null) {+ pending.push(block);+ break;+ }+ this.committed.push(block);+ this.offset = end;+ this.fence = null;+ this.continued = false;+ continue;+ }++ const end = reasoningFragmentEnd(+ source,+ this.offset,+ REASONING_FRAGMENT_CHARACTERS,+ );+ const tail = source.slice(this.offset, end);+ const parsedText = this.prefix + tail;+ const nodes = fromMarkdown(parsedText, {+ extensions: [gfm(), math({ singleDollarTextMath: true })],+ mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown()],+ }).children;+ for (const node of referenceDefinitions(nodes)) {+ const start =+ this.offset + node.position!.start.offset! - this.prefix.length;+ const key = normalizeReference(node.identifier);+ const previous = this.definitions.get(key);+ // CommonMark uses the first definition; only its still-streaming source can change.+ if (previous && previous.start !== start) continue;+ const definition = definitionSource(node);+ if (previous?.source === definition) continue;+ this.definitions.set(key, { start, source: definition });+ }+ // Leave the last node editable (Setext headings, list continuations, open fences).+ const lastStart = Math.max(+ 0,+ (nodes.at(-1)?.position?.start.offset ?? 0) - this.prefix.length,+ );+ if (lastStart > 0) {+ if (nodes.length === 1) {+ this.committed.push({+ start: this.offset,+ end: this.offset + lastStart,+ text: tail.slice(0, lastStart),+ continued: this.continued,+ prefix: this.prefix,+ listContinuationDepth: this.listContinuationDepth,+ tableContinuation: this.tableContinuation,+ });+ }+ for (let n = 0; n < nodes.length - 1; n += 1) {+ const start =+ n === 0+ ? 0+ : Math.max(+ 0,+ nodes[n].position!.start.offset! - this.prefix.length,+ );+ const stop = Math.max(+ 0,+ nodes[n + 1].position!.start.offset! - this.prefix.length,+ );+ this.committed.push({+ start: this.offset + start,+ end: this.offset + stop,+ text: tail.slice(start, stop),+ continued: n === 0 && this.continued,+ prefix: n === 0 ? this.prefix : "",+ listContinuationDepth: n === 0 ? this.listContinuationDepth : 0,+ tableContinuation: n === 0 && this.tableContinuation,+ hidden: nodes[n].type === "definition",+ });+ }+ this.offset += lastStart;+ this.continued = false;+ this.prefix = "";+ this.listContinuationDepth = 0;+ this.tableContinuation = false;+ continue;+ }+ if (end < source.length) {+ // A single enormous paragraph/list/line still has to remain bounded. Prefer a+ // complete line, then whitespace, and keep the continuation visually adjacent.+ let cut = tail.lastIndexOf("\n");+ if (cut < tail.length / 2) cut = tail.lastIndexOf(" ");+ if (cut < tail.length / 2) cut = tail.length;+ else cut += 1;+ this.committed.push({+ start: this.offset,+ end: this.offset + cut,+ text: tail.slice(0, cut),+ continued: this.continued,+ prefix: this.prefix,+ listContinuationDepth: this.listContinuationDepth,+ tableContinuation: this.tableContinuation,+ });+ const context = continuationPrefix(+ parsedText,+ nodes,+ this.prefix.length + cut,+ );+ this.prefix = context.prefix;+ this.listContinuationDepth = context.listDepth;+ this.tableContinuation = Boolean(context.table);+ this.offset += cut;+ this.continued = true;+ continue;+ }+ pending.push({+ start: this.offset,+ end,+ text: tail,+ continued: this.continued,+ prefix: this.prefix,+ listContinuationDepth: this.listContinuationDepth,+ tableContinuation: this.tableContinuation,+ hidden: nodes.every((node) => node.type === "definition"),+ });+ break;+ }+ this.blocks = [...this.committed, ...pending];+ if (+ previousDefinitions.size !== this.definitions.size ||+ [...this.definitions].some(+ ([key, definition]) =>+ previousDefinitions.get(key)?.source !== definition.source,+ )+ )+ this.definitionsRevision += 1;+ }+}++function fragmentsOf(+ block: Block,+ document: number,+ generation: number,+): ReasoningFragment[] {+ const key = `${document}:${generation}:${block.start}`;+ return [+ {+ key,+ document,+ start: block.start,+ end: block.end,+ text: block.text,+ renderText: block.prefix ? block.prefix + block.text : undefined,+ listContinuationDepth: block.listContinuationDepth,+ tableContinuation: block.tableContinuation,+ hidden: block.hidden,+ first: !block.continued,+ last: true,+ },+ ];+}++/** Stored Markdown documents never share fence or paragraph state. */+export class ReasoningTranscriptIndex {+ private documents: DocumentIndex[] = [];+ private fragments = new WeakMap<+ Block,+ {+ revision: number;+ text: string;+ base: ReasoningFragment[];+ rows: ReasoningFragment[];+ }+ >();++ update(sources: readonly string[]): ReasoningFragment[] {+ this.documents.length = sources.length;+ return sources.flatMap((source, document) => {+ const index = (this.documents[document] ??= new DocumentIndex());+ index.update(source);+ return index.blocks.flatMap((block) => {+ // Preview-capable fences retain the established renderer and its settings.+ // Ordinary code keeps the same incremental renderer and scroll geometry.+ if (+ block.fence &&+ (block.text.length > REASONING_FRAGMENT_CHARACTERS ||+ !["mermaid", "svg", "xml", "html"].includes(+ block.fence.language?.toLowerCase() ?? "",+ ))+ ) {+ const fence = block.fence;+ fence.index ??= new ReasoningCodeIndex({+ bodyStart: fence.bodyStart,+ indent: fence.indent,+ language: fence.language,+ key: `${document}:${index.generation}:${block.start}`,+ document,+ start: block.start,+ });+ return fence.index.update(block.text, fence.bodyEnd, fence.incomplete);+ }+ let cached = this.fragments.get(block);+ if (+ !cached ||+ cached.revision !== index.definitionsRevision ||+ cached.text !== block.text+ ) {+ const base =+ cached?.text === block.text+ ? cached.base+ : fragmentsOf(block, document, index.generation);+ const rows = base.map((row) => ({ ...row }));+ if (index.definitions.size) {+ for (const row of rows) {+ if (row.code) continue;+ const rendered = row.renderText ?? row.text;+ const used = new Set<string>();+ for (const match of rendered.matchAll(+ /\[((?:\\.|[^\]\\]){1,999})\]/g,+ )) {+ const definition = index.definitions.get(+ normalizeReference(match[1]),+ );+ if (definition) used.add(definition.source);+ }+ if (used.size)+ row.renderText = [...used].join("\n\n") + "\n\n" + rendered;+ }+ }+ // New definitions only invalidate consumers; ordinary prose and code keep+ // their memoized row identity even when a distant reference is completed.+ if (cached?.text === block.text) {+ for (let i = 0; i < rows.length; i += 1) {+ if (rows[i].renderText === cached.rows[i]?.renderText)+ rows[i] = cached.rows[i];+ }+ }+ cached = {+ revision: index.definitionsRevision,+ text: block.text,+ base,+ rows,+ };+ this.fragments.set(block, cached);+ }+ return cached.rows;+ });+ });+ }+}diff --git a/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx b/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsxnew file mode 100644index 00000000000..813bfa61de1--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/reasoning-transcript.tsx@@ -0,0 +1,579 @@+// 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 {+ defaultRangeExtractor,+ observeElementOffset,+ useVirtualizer,+ type VirtualItem,+} from "@tanstack/react-virtual";+import {+ Fragment as InlineFragment,+ memo,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ CodeBlockActions,+ MarkdownTextSource,+ SearchImagesEnabledContext,+} from "./markdown-text";+import { FenceLine } from "./code-fence-defer";+import {+ useReasoningHighlight,+ type ReasoningLineTokens,+} from "./use-reasoning-highlight";+import {+ ReasoningTranscriptIndex,+ resolveReasoningAnchor,+ type ReasoningReadingAnchor,+ type ReasoningFragment,+} from "./reasoning-transcript-index";+import {+ captureReasoningAnchor,+ reasoningTextRange,+} from "./reasoning-reading-anchor";+import {+ useAdjustForContentInsertedAbove,+ useDetachThreadFromBottom,+} from "./use-intent-aware-autoscroll";+import { cn } from "@/lib/utils";++type Props = {+ initialAnchor?: ReasoningReadingAnchor;+ documents: readonly string[];+ messageId: string;+ messageHasRenderableRenderHtmlTool: boolean;+ streaming: boolean;+};++const CodeFragment = memo(+ function CodeFragment({+ fragment,+ result,+ }: { fragment: ReasoningFragment; result: ReasoningLineTokens }) {+ const code = fragment.code!;+ return (+ <>+ {code.lines.map(({ line, column, text }) => {+ const tokens = result.get(line);+ // A delayed grammar must never display the previous, shorter source.+ if (+ !tokens ||+ tokens+ .map((token) => token.content)+ .join("")+ .slice(column, column + text.length) !== text+ ) {+ return (+ <InlineFragment key={`${line}:${column}`}>+ {column === 0 && line > 0 ? "\n" : ""}+ {text}+ </InlineFragment>+ );+ }+ let offset = 0;+ const clipped = tokens.flatMap((token) => {+ const start = offset;+ offset += token.content.length;+ const content = token.content.slice(+ Math.max(0, column - start),+ Math.max(+ 0,+ Math.min(token.content.length, column + text.length - start),+ ),+ );+ return content ? [{ ...token, content }] : [];+ });+ return (+ <InlineFragment key={`${line}:${column}`}>+ {column === 0 && line > 0 ? "\n" : ""}+ <FenceLine line={clipped} windowed inline />+ </InlineFragment>+ );+ })}+ </>+ );+ },+ (previous, next) => {+ // Appending later lines cannot change this fragment's grammar or text. Keep its+ // highlighted subtree and selection alive instead of repainting it for every token.+ const a = previous.fragment;+ const b = next.fragment;+ return (+ a.key === b.key &&+ a.text === b.text &&+ a.first === b.first &&+ a.last === b.last &&+ a.code?.language === b.code?.language &&+ previous.result.get(a.code!.lines[0].line) ===+ next.result.get(b.code!.lines[0].line)+ );+ },+);++type RowProps = {+ item: VirtualItem;+ fragment: ReasoningFragment;+ top: number;+ measure: (element: HTMLElement | null) => void;+ children: React.ReactNode;+};++function Row({ item, fragment, top, measure, children }: RowProps) {+ return (+ <div+ ref={measure}+ data-index={item.index}+ data-reasoning-fragment={fragment.key}+ className="absolute top-0 left-0 w-full min-w-0"+ style={{+ transform: `translateY(${item.start - top}px)`,+ contain: "layout style",+ }}+ >+ {children}+ </div>+ );+}++function CodeGroup({+ items,+ fragments,+ top,+ measure,+ streaming,+}: {+ items: VirtualItem[];+ fragments: ReasoningFragment[];+ top: number;+ measure: RowProps["measure"];+ streaming: boolean;+}) {+ const surface = useRef<HTMLDivElement>(null);+ useLayoutEffect(() => {+ const element = surface.current;+ if (!element) return;+ // ResizeObserver does not report inline span geometry. Observe their shared+ // formatting surface and feed each bounded row's measured contribution back.+ const observer = new ResizeObserver(() => {+ for (const row of element.querySelectorAll<HTMLElement>(+ "[data-reasoning-code-row]",+ ))+ measure(row);+ });+ observer.observe(element);+ return () => observer.disconnect();+ }, [measure]);+ const code = fragments[items[0].index].code!;+ // One highlighter subscription per visible fence, with its complete grammar context.+ const lines = [+ ...new Set(+ items.flatMap((item) =>+ fragments[item.index].code!.lines.map((line) => line.line),+ ),+ ),+ ];+ const result = useReasoningHighlight(code.source, code.language, lines);+ const first = fragments[items[0].index];+ const last = fragments[items.at(-1)!.index];+ return (+ <div+ ref={surface}+ data-slot="reasoning-code-fragment"+ data-language={code.language ?? undefined}+ className={cn(+ "aui-reasoning-code-fragment absolute top-0 left-0 w-full min-w-0",+ first.first && "aui-reasoning-code-first",+ last.last && "aui-reasoning-code-last",+ )}+ style={{ transform: `translateY(${items[0].start - top}px)` }}+ >+ {first.first && (+ <CodeBlockActions+ disabled={streaming && code.incomplete}+ language={code.language}+ source={code.source}+ />+ )}+ {first.first && (+ <div className="mb-2 min-h-4 pr-20 text-xs text-muted-foreground">+ {code.language}+ </div>+ )}+ <pre className="!m-0 min-h-[1lh] whitespace-pre-wrap [overflow-wrap:anywhere] font-mono">+ <code>+ {items.map((item, i) => (+ <InlineFragment key={item.key}>+ {i > 0 && items[i - 1].index + 1 !== item.index && (+ <span+ aria-hidden="true"+ data-reasoning-code-gap=""+ className="block"+ style={{ height: Math.max(0, item.start - items[i - 1].end) }}+ />+ )}+ <span+ ref={measure}+ data-index={item.index}+ data-reasoning-fragment={fragments[item.index].key}+ data-reasoning-code-row=""+ >+ <CodeFragment+ fragment={fragments[item.index]}+ result={result}+ />+ </span>+ </InlineFragment>+ ))}+ </code>+ </pre>+ </div>+ );+}++const Fragment = memo(function Fragment({+ fragment,+ messageId,+ messageHasRenderableRenderHtmlTool,+ streaming,+}: Omit<Props, "documents"> & { fragment: ReasoningFragment }) {+ const root = useRef<HTMLDivElement>(null);+ useLayoutEffect(() => {+ // Continuation containers preserve indentation/numbering but must not paint+ // another bullet for the same item. Later, real siblings retain their markers.+ const items: HTMLElement[] = [];+ let container: Element | null | undefined = root.current?.firstElementChild;+ for (+ let depth = 0;+ depth < (fragment.listContinuationDepth ?? 0);+ depth += 1+ ) {+ while (+ container?.firstElementChild &&+ ["DIV", "BLOCKQUOTE"].includes(container.firstElementChild.tagName)+ )+ container = container.firstElementChild;+ const item: HTMLElement | null | undefined = container?.querySelector(+ ":scope > :is(ol, ul):first-child > li:first-child",+ );+ if (!item) break;+ item.dataset.reasoningListContinuation = "";+ items.push(item);+ container = item;+ }+ return () => {+ for (const item of items) delete item.dataset.reasoningListContinuation;+ };+ }, [fragment]);+ if (fragment.hidden) return null;+ return (+ <div+ ref={root}+ data-table-continuation={fragment.tableContinuation || undefined}+ className={cn("aui-reasoning-prose-fragment", fragment.first && "pt-4")}+ >+ <MarkdownTextSource+ messageId={messageId}+ messageHasRenderableRenderHtmlTool={messageHasRenderableRenderHtmlTool}+ sourceText={fragment.renderText ?? fragment.text}+ streaming={streaming}+ />+ </div>+ );+});++export function ReasoningTranscript({+ initialAnchor,+ documents,+ messageId,+ messageHasRenderableRenderHtmlTool,+ streaming,+}: Props) {+ const root = useRef<HTMLDivElement>(null);+ const [index] = useState(() => new ReasoningTranscriptIndex());+ const fragments = useMemo(() => index.update(documents), [documents, index]);+ const [anchor, setAnchor] = useState(+ () => initialAnchor && resolveReasoningAnchor(fragments, initialAnchor),+ );+ const [anchoring, setAnchoring] = useState(+ Boolean(anchor && anchor.index >= 0),+ );+ const [geometry, setGeometry] = useState({+ top: 0,+ width: 640,+ lineHeight: 24,+ fontPixels: 15,+ });+ const [protectedKeys, setProtectedKeys] = useState<Set<string>>(+ () => new Set(),+ );+ const adjustAbove = useAdjustForContentInsertedAbove();+ const detach = useDetachThreadFromBottom();+ const viewport = useCallback(+ () => root.current?.closest<HTMLDivElement>(".aui-thread-viewport") ?? null,+ [],+ );++ const virtualizer = useVirtualizer<HTMLDivElement, HTMLElement>({+ count: fragments.length,+ getScrollElement: viewport,+ getItemKey: (i) => fragments[i].key,+ scrollMargin: geometry.top,+ initialOffset: () => viewport()?.scrollTop ?? 0,+ observeElementOffset: (instance, callback) => {+ // The viewport predates this transcript. Subscribe with its current offset;+ // waiting for the next scroll event leaves TanStack's initial zero cached.+ callback(instance.scrollElement?.scrollTop ?? 0, false);+ return observeElementOffset(instance, callback);+ },+ overscan: 2,+ measureElement: (element) => {+ if (!element.hasAttribute("data-reasoning-code-row"))+ return element.getBoundingClientRect().height;+ const surface = element.closest<HTMLElement>(+ '[data-slot="reasoning-code-fragment"]',+ )!;+ const previous = element.previousElementSibling;+ const bottom = element.nextElementSibling+ ? element.getBoundingClientRect().bottom+ : surface.getBoundingClientRect().bottom;+ const top = previous+ ? previous.getBoundingClientRect().bottom+ : surface.getBoundingClientRect().top;+ const margin = previous+ ? 0+ : Number.parseFloat(getComputedStyle(surface).marginTop) || 0;+ return Math.max(0, bottom - top + margin);+ },+ estimateSize: (i) => {+ const fragment = fragments[i];+ if (fragment.hidden) return 0;+ const code = fragment.code;+ const columns = Math.max(+ 12,+ Math.floor(+ (geometry.width - (code ? 32 : 0)) /+ (geometry.fontPixels * (code ? 0.58 : 0.48)),+ ),+ );+ const lines = fragment.text+ .split("\n")+ .reduce(+ (sum, line) => sum + Math.max(1, Math.ceil(line.length / columns)),+ 0,+ );+ return code+ ? lines * geometry.lineHeight ++ (fragment.first ? 40 : 0) ++ (fragment.last ? 16 : 0)+ : Math.max(1, lines - 2) * geometry.lineHeight ++ (fragment.first ? 16 : 0);+ },+ rangeExtractor: (range) => {+ const mounted = new Set(defaultRangeExtractor(range));+ if (anchoring && anchor) mounted.add(anchor.index);+ if (protectedKeys.size)+ fragments.forEach((fragment, i) => {+ if (protectedKeys.has(fragment.key)) mounted.add(i);+ });+ return [...mounted].sort((a, b) => a - b);+ },+ // TanStack reports measurement corrections; the thread controller owns all scroll writes.+ // Its own initial-position writes are intentionally ignored.+ scrollToFn: (offset, { adjustments }) => {+ const element = viewport();+ if (element && adjustments !== undefined)+ adjustAbove(offset + adjustments - element.scrollTop);+ },+ });+ virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item) =>+ // Ref measurements run before the virtualizer observes the shared viewport.+ // Its offset is still zero then: applying that correction would send a reader+ // back to the beginning when a live trace first crosses the threshold.+ virtualizer.scrollElement !== null &&+ item.end < (viewport()?.scrollTop ?? 0);++ useLayoutEffect(() => {+ const element = root.current;+ const scroll = viewport();+ if (!element || !scroll) return;+ let frame = 0;+ let width = 0;+ let readingAnchor: (ReasoningReadingAnchor & { index: number }) | undefined;+ const measure = () => {+ frame = 0;+ const rect = element.getBoundingClientRect();+ if (!rect.width) return;+ const style = getComputedStyle(element);+ const next = {+ top: rect.top - scroll.getBoundingClientRect().top + scroll.scrollTop,+ width: rect.width,+ lineHeight: Number.parseFloat(style.lineHeight) || 24,+ fontPixels: Number.parseFloat(style.fontSize) || 15,+ };+ setGeometry((old) =>+ Object.keys(next).every(+ (key) =>+ next[key as keyof typeof next] === old[key as keyof typeof old],+ )+ ? old+ : next,+ );+ if (width && width !== rect.width) {+ // Capture before reflow: a long user message above us may push the whole+ // transcript offscreen at the new width before ResizeObserver runs.+ if (readingAnchor) {+ setAnchor(readingAnchor);+ setAnchoring(true);+ }+ virtualizer.measure();+ } else {+ readingAnchor = undefined;+ for (const row of element.querySelectorAll<HTMLElement>(+ "[data-index]",+ )) {+ const captured = captureReasoningAnchor(row, scroll);+ if (captured) {+ readingAnchor = { ...captured, index: Number(row.dataset.index) };+ break;+ }+ }+ }+ width = rect.width;+ };+ const schedule = () => {+ if (!frame) frame = requestAnimationFrame(measure);+ };+ const observer = new ResizeObserver(schedule);+ observer.observe(element);+ observer.observe(scroll);+ if (scroll.firstElementChild) observer.observe(scroll.firstElementChild);+ scroll.addEventListener("scroll", schedule, { passive: true });+ measure();+ return () => {+ observer.disconnect();+ scroll.removeEventListener("scroll", schedule);+ cancelAnimationFrame(frame);+ };+ }, [viewport, virtualizer]);++ useLayoutEffect(() => {+ if (!anchoring || !anchor) return;+ // Keep this passage mounted through the initial estimates, then reconcile its+ // measured position through the thread's single scroll owner before releasing it.+ const frame = requestAnimationFrame(() => {+ const row = root.current?.querySelector(`[data-index="${anchor.index}"]`);+ const passage =+ row && reasoningTextRange(row, anchor.text, anchor.occurrence);+ if (passage)+ adjustAbove(passage.getBoundingClientRect().top - anchor.top);+ setAnchoring(false);+ });+ return () => cancelAnimationFrame(frame);+ }, [anchor, anchoring, adjustAbove]);++ useEffect(() => {+ const element = root.current;+ if (!element) return;+ const protect = () => {+ const selection = window.getSelection();+ const keys = new Set<string>();+ for (const row of element.querySelectorAll<HTMLElement>(+ "[data-reasoning-fragment]",+ )) {+ const focused =+ document.activeElement && row.contains(document.activeElement);+ let selected = false;+ if (selection && !selection.isCollapsed) {+ for (let i = 0; i < selection.rangeCount; i += 1)+ selected ||= selection.getRangeAt(i).intersectsNode(row);+ }+ if (selected || focused) keys.add(row.dataset.reasoningFragment!);+ }+ if (keys.size) detach();+ setProtectedKeys((old) =>+ old.size === keys.size && [...old].every((key) => keys.has(key))+ ? old+ : keys,+ );+ };+ document.addEventListener("selectionchange", protect);+ element.addEventListener("focusin", protect);+ element.addEventListener("focusout", protect);+ return () => {+ document.removeEventListener("selectionchange", protect);+ element.removeEventListener("focusin", protect);+ element.removeEventListener("focusout", protect);+ };+ }, [detach]);++ const groups: {+ key: string;+ code: boolean;+ items: VirtualItem[];+ }[] = [];+ for (const item of virtualizer.getVirtualItems()) {+ const fragment = fragments[item.index];+ const key = fragment.code+ ? `${fragment.document}:${fragment.start}`+ : fragment.key;+ const previous = groups.at(-1);+ if (previous?.key === key) previous.items.push(item);+ else+ groups.push({+ key,+ code: Boolean(fragment.code),+ items: [item],+ });+ }++ return (+ <SearchImagesEnabledContext.Provider value={false}>+ <div+ ref={root}+ data-slot="reasoning-transcript"+ className="relative min-w-0"+ style={{ height: virtualizer.getTotalSize(), overflowAnchor: "none" }}+ >+ {groups.map((group) => {+ if (group.code)+ return (+ <CodeGroup+ key={group.key}+ items={group.items}+ fragments={fragments}+ top={geometry.top}+ measure={virtualizer.measureElement}+ streaming={streaming}+ />+ );+ const item = group.items[0];+ const fragment = fragments[item.index];+ return (+ <Row+ key={item.key}+ item={item}+ fragment={fragment}+ top={geometry.top}+ measure={virtualizer.measureElement}+ >+ <Fragment+ fragment={fragment}+ messageId={messageId}+ messageHasRenderableRenderHtmlTool={+ messageHasRenderableRenderHtmlTool+ }+ streaming={streaming && item.index === fragments.length - 1}+ />+ </Row>+ );+ })}+ </div>+ </SearchImagesEnabledContext.Provider>+ );+}diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsxindex d7fab9782a9..d3b6d33c137 100644--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx@@ -7,16 +7,14 @@import {MarkdownText,- MarkdownTextSource,SearchImagesEnabledContext,} from "@/components/assistant-ui/markdown-text";import {- type ReasoningPageBoundary,- ReasoningPageSelector,- createReasoningPageBoundary,- isReasoningPageBoundaryValid,- shouldPaginateReasoning,-} from "@/components/assistant-ui/reasoning-pagination";+ REASONING_TRANSCRIPT_THRESHOLD,+ type ReasoningReadingAnchor,+} from "./reasoning-transcript-index";+import { ReasoningTranscript } from "./reasoning-transcript";+import { captureReasoningAnchor } from "./reasoning-reading-anchor";import {Collapsible,CollapsibleContent,@@ -32,9 +30,9 @@ import {import {clearReasoningRound,foldIsActive,+ isRenderableRenderHtmlToolPart,resolveReasoningGroupDuration,resolveReasoningOpen,- resolveReasoningToggle,setReasoningRoundOpen,startsNewReasoningRound,useChatPreferencesStore,@@ -53,7 +51,6 @@ import {reasoningRoundKey,} from "@/components/assistant-ui/thinking-fold";import { toolRunIsExempt } from "@/components/assistant-ui/tool-fold-exemptions";-import { isRenderableRenderHtmlToolPart } from "@/features/chat/artifacts/html-fences";import { useDetachThreadFromBottom } from "@/components/assistant-ui/use-intent-aware-autoscroll";import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";import { formatWorkedFor } from "@/lib/format-worked-for";@@ -79,14 +76,11 @@ import {useCallback,useEffect,useLayoutEffect,- useMemo,useRef,useState,} from "react";import { useShallow } from "zustand/react/shallow";-import { ScrollPane } from "./scroll-pane";const ANIMATION_DURATION = 200;-const AUTO_SCROLL_THRESHOLD_PX = 24;function selectionIntersectsElement(selection: Selection | null,@@ -156,9 +150,9 @@ function ReasoningRoot({const handleOpenChange = useCallback((open: boolean) => {- if (!open) {- lockScroll();- }+ // Native scroll anchoring can move the focused header when a long transcript+ // opens below it. Preserve its position through either direction of the animation.+ lockScroll();if (!isControlled) {setUncontrolledOpen(open);}@@ -173,7 +167,10 @@ function ReasoningRoot({"data-variant": variant,open: isOpen,onOpenChange: handleOpenChange,- className: cn("group/reasoning-root", reasoningVariants({ variant, className })),+ className: cn(+ "group/reasoning-root",+ reasoningVariants({ variant, className }),+ ),style: {"--animation-duration": `${ANIMATION_DURATION}ms`,} as CSSProperties,@@ -273,6 +270,7 @@ function ReasoningContent({return (<UnmeasuredCollapsibleContentdata-slot="reasoning-content"+ data-streaming={streaming ? "" : undefined}closeDurationMs={ANIMATION_DURATION}className={cn(shared,@@ -298,6 +296,7 @@ function ReasoningContent({return (<CollapsibleContentdata-slot="reasoning-content"+ data-streaming={streaming ? "" : undefined}className={cn(shared,"data-[state=closed]:animate-collapsible-up",@@ -315,79 +314,14 @@ function ReasoningContent({}function ReasoningText({- autoScroll,className,- pageKey,streaming,+ virtualized = false,children,...props-}: ComponentProps<"div"> & {- autoScroll?: boolean;- pageKey?: string;- streaming?: boolean;-}) {- const scrollRef = useRef<HTMLDivElement>(null);- const shouldAutoScrollRef = useRef(true);- const detachedFromBottomRef = useRef(false);- const lastScrollTopRef = useRef(0);-- useEffect(() => {- if (!(streaming && (autoScroll ?? true) && scrollRef.current)) {- return;- }- const el = scrollRef.current;- el.scrollTop = el.scrollHeight;- const updateAutoScroll = () => {- const currentScrollTop = el.scrollTop;- if (currentScrollTop < lastScrollTopRef.current) {- detachedFromBottomRef.current = true;- }- const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;- if (- detachedFromBottomRef.current &&- distanceFromBottom <= AUTO_SCROLL_THRESHOLD_PX- ) {- detachedFromBottomRef.current = false;- }- shouldAutoScrollRef.current = !detachedFromBottomRef.current;- lastScrollTopRef.current = currentScrollTop;- };- const handleWheel = (event: WheelEvent) => {- if (event.deltaY < 0) {- detachedFromBottomRef.current = true;- shouldAutoScrollRef.current = false;- }- };- const observer = new MutationObserver(() => {- if (shouldAutoScrollRef.current) {- el.scrollTop = el.scrollHeight;- }- });- el.addEventListener("scroll", updateAutoScroll);- el.addEventListener("wheel", handleWheel, { passive: true });- observer.observe(el, {- childList: true,- subtree: true,- characterData: true,- });- lastScrollTopRef.current = el.scrollTop;- detachedFromBottomRef.current = false;- updateAutoScroll();- return () => {- observer.disconnect();- el.removeEventListener("scroll", updateAutoScroll);- el.removeEventListener("wheel", handleWheel);- };- }, [autoScroll, streaming]);-- useEffect(() => {- if (autoScroll === false && scrollRef.current) {- scrollRef.current.scrollTop = 0;- }- }, [autoScroll, pageKey]);+}: ComponentProps<"div"> & { streaming?: boolean; virtualized?: boolean }) {return (<div- ref={scrollRef}data-slot="reasoning-text"data-streaming={streaming ? "" : undefined}className={cn(@@ -395,15 +329,18 @@ function ReasoningText({// fade. The thread's own follow-scroll tracks it while it streams."aui-reasoning-text relative z-0 pt-4 pb-0 leading-relaxed","[&_p]:my-0 [&_p+p]:mt-4 [&_ul]:my-4 [&_ol]:my-4 [&_pre]:my-4",- "transform-gpu transition-[transform,opacity]",- "group-data-[state=open]/collapsible-content:animate-in",- "group-data-[state=closed]/collapsible-content:animate-out",- "group-data-[state=open]/collapsible-content:fade-in-0",- "group-data-[state=closed]/collapsible-content:fade-out-0",- "group-data-[state=open]/collapsible-content:slide-in-from-top-4",- "group-data-[state=closed]/collapsible-content:slide-out-to-top-4",- "group-data-[state=open]/collapsible-content:duration-(--animation-duration)",- "group-data-[state=closed]/collapsible-content:duration-(--animation-duration)",+ !virtualized &&+ cn(+ "transform-gpu transition-[transform,opacity]",+ "group-data-[state=open]/collapsible-content:animate-in",+ "group-data-[state=closed]/collapsible-content:animate-out",+ "group-data-[state=open]/collapsible-content:fade-in-0",+ "group-data-[state=closed]/collapsible-content:fade-out-0",+ "group-data-[state=open]/collapsible-content:slide-in-from-top-4",+ "group-data-[state=closed]/collapsible-content:slide-out-to-top-4",+ "group-data-[state=open]/collapsible-content:duration-(--animation-duration)",+ "group-data-[state=closed]/collapsible-content:duration-(--animation-duration)",+ ),className,)}{...props}@@ -421,80 +358,6 @@ const ReasoningImpl: ReasoningMessagePartComponent = () => (const COPY_RESET_MS = 2000;-function ReasoningPageNavigation({- hasEarlier,- hasNewer,- onEarlier,- onLatest,- onNewer,- start,- end,- total,-}: {- hasEarlier: boolean;- hasNewer: boolean;- onEarlier: () => void;- onLatest: () => void;- onNewer: () => void;- start: number;- end: number;- total: number;-}) {- const buttonClass =- "rounded px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40";- return (- <nav- data-slot="reasoning-page-navigation"- aria-label="Reasoning pages"- className="flex min-w-0 flex-wrap items-center gap-1 border-b border-border/60 py-1"- >- <button- type="button"- className={buttonClass}- disabled={!hasEarlier}- onClick={onEarlier}- >- Earlier- </button>- <button- type="button"- className={buttonClass}- disabled={!hasNewer}- onClick={onNewer}- >- Newer- </button>- <button- type="button"- className={buttonClass}- disabled={!hasNewer}- onClick={onLatest}- >- Latest- </button>- <span className="ml-auto truncate text-xs text-muted-foreground tabular-nums">- {start + 1}–{end} of {total}- </span>- </nav>- );-}--function OversizedReasoningCode({ source }: { source: string }) {- return (- <div data-slot="reasoning-oversized-code" className="min-w-0">- <p className="mb-2 rounded bg-muted/50 px-2 py-1.5 text-xs text-muted-foreground">- Showing part of an oversized code block. Copy reasoning preserves the- full source.- </p>- <ScrollPane- className="max-w-full rounded-md bg-muted/40 p-3"- scrollerClassName="overflow-x-auto whitespace-pre-wrap break-words font-mono text-xs"- >- {source}- </ScrollPane>- </div>- );-}function ReasoningCopyButton({startIndex,endIndex,@@ -532,54 +395,51 @@ function ReasoningCopyButton({);}-// Paging for a long trace, shared by the lead block and the rounds folded inside it so a long-// later round is protected the same way the first one is.-function useReasoningPages({+// Keep an existing selection intact when a live trace crosses the windowing threshold.+// An already-long saved trace is bounded on its first render.+function useReasoningTranscriptMode({messageId,reasoningDocuments,- isStreaming,reasoningContentRef,}: {messageId: string;reasoningDocuments: readonly string[];- isStreaming: boolean;reasoningContentRef: RefObject<HTMLDivElement | null>;}) {- const reasoningText = reasoningDocuments.join("");- const wantsPagination = shouldPaginateReasoning(reasoningText);- const [storedPaginationSession, setPaginationSession] = useState(() => ({- history: [] as ReasoningPageBoundary[],- messageId,- started: wantsPagination,- }));- const paginationSession =- storedPaginationSession.messageId === messageId- ? storedPaginationSession- : { history: [], messageId, started: wantsPagination };- if (paginationSession !== storedPaginationSession) {- setPaginationSession(paginationSession);- }- const pageSelector = useMemo(() => new ReasoningPageSelector(), [messageId]);-- // An already-long saved trace paginates on its first render. Only the live- // transition from short to long waits for an active selection to finish.+ const wantsWindow =+ reasoningDocuments.reduce((sum, text) => sum + text.length, 0) >+ REASONING_TRANSCRIPT_THRESHOLD;+ const [session, setSession] = useState<{+ messageId: string;+ active: boolean;+ anchor?: ReasoningReadingAnchor;+ }>({ messageId, active: wantsWindow });useEffect(() => {- if (!wantsPagination) {- if (paginationSession.started || paginationSession.history.length > 0) {- setPaginationSession({ history: [], messageId, started: false });- }- return;- }- if (paginationSession.started) {- return;- }-- const startPagination = () => {- setPaginationSession((current) =>- current.messageId === messageId- ? { ...current, started: true }- : { history: [], messageId, started: true },- );+ if (!session.anchor) return;+ // The transcript captures this only on its first mount. Reopening the block+ // later must not replay a reading position from the threshold transition.+ const timer = setTimeout(+ () => setSession((current) => ({ ...current, anchor: undefined })),+ 0,+ );+ return () => clearTimeout(timer);+ }, [session.anchor]);+ if (session.messageId !== messageId || (!wantsWindow && session.active))+ setSession({ messageId, active: wantsWindow });+ useEffect(() => {+ if (!wantsWindow) return;+ if (session.active) return;+ const activate = () => {+ const content = reasoningContentRef.current;+ const viewport = content?.closest(".aui-thread-viewport");+ setSession({+ messageId,+ active: true,+ anchor:+ content && viewport+ ? captureReasoningAnchor(content, viewport)+ : undefined,+ });};if (!selectionIntersectsElement(@@ -587,8 +447,8 @@ function useReasoningPages({reasoningContentRef.current,)) {- startPagination();- return;+ const timer = setTimeout(activate, 0);+ return () => clearTimeout(timer);}const handleSelectionChange = () => {if (@@ -596,152 +456,57 @@ function useReasoningPages({window.getSelection(),reasoningContentRef.current,)- ) {- startPagination();- }+ )+ activate();};document.addEventListener("selectionchange", handleSelectionChange);return () =>document.removeEventListener("selectionchange", handleSelectionChange);- }, [messageId, paginationSession, wantsPagination]);-- const historyIsValid = paginationSession.history.every((boundary) =>- isReasoningPageBoundaryValid(reasoningText, boundary),- );- useEffect(() => {- if (!historyIsValid) {- setPaginationSession((current) =>- current.messageId === messageId- ? { ...current, history: [] }- : current,- );- }- }, [historyIsValid, messageId]);- const validHistory = historyIsValid ? paginationSession.history : [];- const selectedEnd = validHistory.at(-1)?.end ?? null;- const paginationActive = paginationSession.started && wantsPagination;- const page = useMemo(- () =>- pageSelector.selectDocument(reasoningDocuments, {- end: paginationActive ? selectedEnd : reasoningText.length,-- streaming:- paginationActive && isStreaming && selectedEnd === null,- }),- [- isStreaming,- pageSelector,- paginationActive,- reasoningDocuments,- reasoningText,- selectedEnd,- ],- );- const viewingLatestPage = !(paginationActive && page.hasNewer);-- const showEarlierPage = useCallback(() => {- if (!page.hasEarlier) {- return;- }- setPaginationSession((current) =>- current.messageId === messageId- ? {- ...current,- history: [- ...current.history,- createReasoningPageBoundary(reasoningText, page.start),- ],- }- : current,- );- }, [messageId, page.hasEarlier, page.start, reasoningText]);- const showNewerPage = useCallback(() => {- setPaginationSession((current) =>- current.messageId === messageId- ? { ...current, history: current.history.slice(0, -1) }- : current,- );- }, [messageId]);- const showLatestPage = useCallback(() => {- setPaginationSession((current) =>- current.messageId === messageId ? { ...current, history: [] } : current,- );- }, [messageId]);-+ }, [messageId, reasoningContentRef, session.active, wantsWindow]);return {- reasoningText,- paginationActive,- page,- viewingLatestPage,- showEarlierPage,- showNewerPage,- showLatestPage,+ active:+ wantsWindow && (session.messageId === messageId ? session.active : true),+ documents: reasoningDocuments,+ anchor: session.anchor,};}-type ReasoningPages = ReturnType<typeof useReasoningPages>;-function ReasoningBody({- pages,+ transcript,messageId,messageHasRenderableRenderHtmlTool,isStreaming,- retainStreamingHeight = false,textClassName,children,}: {- pages: ReasoningPages;+ transcript: ReturnType<typeof useReasoningTranscriptMode>;messageId: string;messageHasRenderableRenderHtmlTool: boolean;isStreaming: boolean;- retainStreamingHeight?: boolean;textClassName?: string;children: ReactNode;}) {- const { page, paginationActive, reasoningText, viewingLatestPage } = pages;return (- <>- {paginationActive && (- <ReasoningPageNavigation- hasEarlier={page.hasEarlier}- hasNewer={page.hasNewer}- onEarlier={pages.showEarlierPage}- onNewer={pages.showNewerPage}- onLatest={pages.showLatestPage}- start={page.start}- end={page.end}- total={reasoningText.length}+ <ReasoningText+ className={textClassName}+ streaming={isStreaming}+ virtualized={transcript.active}+ >+ {transcript.active ? (+ <ReasoningTranscript+ key={messageId}+ initialAnchor={transcript.anchor}+ documents={transcript.documents}+ messageId={messageId}+ messageHasRenderableRenderHtmlTool={+ messageHasRenderableRenderHtmlTool+ }+ streaming={isStreaming}/>+ ) : (+ children)}- <ReasoningText- autoScroll={viewingLatestPage}- className={textClassName}- pageKey={paginationActive ? `${page.start}:${page.end}` : undefined}- streaming={isStreaming || retainStreamingHeight}- >- {paginationActive ? (- <>- {page.oversizedCode ? (- <OversizedReasoningCode source={page.markdown} />- ) : (- <SearchImagesEnabledContext.Provider value={false}>- <MarkdownTextSource- key={`${page.documentIndex}:${page.start}`}- messageHasRenderableRenderHtmlTool={- messageHasRenderableRenderHtmlTool- }- messageId={messageId}- sourceText={page.markdown}- streaming={isStreaming && viewingLatestPage}- />- </SearchImagesEnabledContext.Provider>- )}- </>- ) : (- children- )}- </ReasoningText>- </>+ </ReasoningText>);}@@ -754,7 +519,8 @@ const ReasoningGroupImpl: ReasoningGroupComponent = (props) => {);const folded = useAuiState(({ message }) =>- foldToolActivity && isFoldedReasoningGroup(message.parts, props.startIndex),+ foldToolActivity &&+ isFoldedReasoningGroup(message.parts, props.startIndex),);if (folded) {return <FoldedReasoningRound {...props} />;@@ -810,10 +576,9 @@ const FoldedReasoningRound: ReasoningGroupComponent = ({.map((part) => ("text" in part ? (part as { text: string }).text : "")),),);- const pages = useReasoningPages({+ const transcript = useReasoningTranscriptMode({messageId,reasoningDocuments,- isStreaming,reasoningContentRef,});const closesTrace = useAuiState(({ message }) =>@@ -827,7 +592,7 @@ const FoldedReasoningRound: ReasoningGroupComponent = ({className={cn(!open && "hidden")}><ReasoningBody- pages={pages}+ transcript={transcript}messageId={messageId}messageHasRenderableRenderHtmlTool={messageHasRenderableRenderHtmlTool}isStreaming={isStreaming}@@ -900,10 +665,9 @@ const ReasoningGroupBlock = ({.map((part) => ("text" in part ? (part as { text: string }).text : "")),),);- const pages = useReasoningPages({+ const transcript = useReasoningTranscriptMode({messageId,reasoningDocuments,- isStreaming: isReasoningStreaming,reasoningContentRef,});@@ -925,7 +689,6 @@ const ReasoningGroupBlock = ({// null until toggled by hand, then it outranks the setting for the round.const [override, setOverride] = useState<boolean | null>(null);- const [retainStreamingHeight, setRetainStreamingHeight] = useState(false);const [duration, setDuration] = useState<number>(0);const startTimeRef = useRef<number | null>(null);@@ -965,27 +728,6 @@ const ReasoningGroupBlock = ({override,});- // Keep the streaming height cap until the automatic close finishes. Removing it on the completion- // frame expands long reasoning to its full height before the collapsible can close, which makes- // the entire chat jump. The grid path needs the same margin the collapsible's own backstop uses.- // The height keyframes animate from a height captured at toggle time, so releasing the cap- // mid-animation cannot change what they animate; `1fr` instead resolves against the live content- // every frame, so an early release grows the row in the middle of the collapse and produces- // exactly the jump this timer prevents. The transition also starts a render after this timer is- // armed, so an exact ANIMATION_DURATION lands inside it. A block the setting keeps open past- // its stream has no collapse to wait out and grows into its full height when this fires. isOpen- // is deliberately not a dependency: re-running on a manual open would re-arm the cap that- // handleOpenChange just released.- useEffect(() => {- const closeDelay = GRID_COLLAPSE_REASONING_ENABLED- ? ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS- : ANIMATION_DURATION;- const timeout = window.setTimeout(- () => setRetainStreamingHeight(isReasoningStreaming),- isReasoningStreaming ? 0 : closeDelay,- );- return () => window.clearTimeout(timeout);- }, [isReasoningStreaming]);// Publish the lead's open state for everything folded under it, and count the tool calls for// its header. A layout effect, so the folded parts settle before the frame the user sees.const roundKey = reasoningRoundKey(messageId, endIndex);@@ -1019,19 +761,12 @@ const ReasoningGroupBlock = ({const detachFromBottom = useDetachThreadFromBottom();const handleOpenChange = useCallback((open: boolean) => {- if (open && !isReasoningStreaming) {+ if (open) {detachFromBottom();}- const next = resolveReasoningToggle(open, {- isStreaming: isReasoningStreaming,- visibility,- });- if (next.releaseStreamingHeight) {- setRetainStreamingHeight(false);- }- setOverride(next.override);+ setOverride(open);},- [isReasoningStreaming, visibility, detachFromBottom],+ [detachFromBottom],);return (@@ -1062,11 +797,12 @@ const ReasoningGroupBlock = ({ref={reasoningContentRef}><ReasoningBody- pages={pages}+ transcript={transcript}messageId={messageId}- messageHasRenderableRenderHtmlTool={messageHasRenderableRenderHtmlTool}+ messageHasRenderableRenderHtmlTool={+ messageHasRenderableRenderHtmlTool+ }isStreaming={isReasoningStreaming}- retainStreamingHeight={retainStreamingHeight}>{children}</ReasoningBody>diff --git a/studio/frontend/src/components/assistant-ui/use-reasoning-highlight.ts b/studio/frontend/src/components/assistant-ui/use-reasoning-highlight.tsnew file mode 100644index 00000000000..8d1c22b0ed7--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/use-reasoning-highlight.ts@@ -0,0 +1,93 @@+// 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 { useEffect, useRef, useState } from "react";+import type {+ ReasoningHighlightReply,+ ReasoningHighlightRequest,+} from "./reasoning-highlight";++export type ReasoningLineTokens = Map<+ number,+ ReasoningHighlightReply["lines"][number]["tokens"]+>;+let worker: Worker | null = null;+let nextClient = 0;+let idle: ReturnType<typeof setTimeout> | undefined;+const listeners = new Map<number, (reply: ReasoningHighlightReply) => void>();++function getWorker(): Worker | null {+ if (idle) clearTimeout(idle);+ if (worker) return worker;+ if (typeof Worker === "undefined") return null;+ try {+ worker = new Worker(+ new URL("./reasoning-highlight.worker.ts", import.meta.url),+ { type: "module" },+ );+ worker.onmessage = ({ data }: MessageEvent<ReasoningHighlightReply>) =>+ listeners.get(data.client)?.(data);+ worker.onerror = () => {+ worker?.terminate();+ worker = null;+ };+ return worker;+ } catch {+ return null;+ }+}++/** Text is synchronous; expensive grammar work must never hold up chat or scrolling. */+export function useReasoningHighlight(+ source: string,+ language: string | null,+ lines: number[],+): ReasoningLineTokens {+ const [tokens, setTokens] = useState<ReasoningLineTokens>(() => new Map());+ const client = useRef<number | null>(null);+ const revision = useRef(0);+ const sent = useRef<{ worker: Worker; source: string } | null>(null);+ const lineKey = lines.join(",");+ useEffect(() => {+ const instance = getWorker();+ if (!instance) return;+ const id = (client.current ??= ++nextClient);+ const version = ++revision.current;+ listeners.set(id, (reply) => {+ if (reply.revision !== version) return;+ setTokens(new Map(reply.lines.map(({ line, tokens }) => [line, tokens])));+ });+ const request: ReasoningHighlightRequest = {+ client: id,+ revision: version,+ source:+ sent.current?.worker === instance &&+ source.startsWith(sent.current.source)+ ? {+ from: sent.current.source.length,+ text: source.slice(sent.current.source.length),+ }+ : source,+ language,+ lines: lineKey.split(",").filter(Boolean).map(Number),+ };+ instance.postMessage(request);+ sent.current = { worker: instance, source };+ }, [source, language, lineKey]);+ useEffect(+ () => () => {+ if (client.current !== null) {+ sent.current = null;+ listeners.delete(client.current);+ worker?.postMessage({ cancel: client.current });+ }+ if (listeners.size === 0)+ idle = setTimeout(() => {+ worker?.terminate();+ worker = null;+ }, 10_000);+ },+ [],+ );+ return tokens;+}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 70244d3059e..c33b7e5b643 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export { ChatPage, validateChatSearch, type ChatSearch } from "./chat-page";+export { isRenderableRenderHtmlToolPart } from "./artifacts/html-fences";export {addScanFolder,browseFolders,@@ -331,7 +332,6 @@ export { resolveReasoningGroupDuration } from "./utils/reasoning-duration";export {reasoningFollowsPreference,resolveReasoningOpen,- resolveReasoningToggle,startsNewReasoningRound,} from "./utils/reasoning-visibility";export {diff --git a/studio/frontend/src/features/chat/utils/reasoning-visibility.ts b/studio/frontend/src/features/chat/utils/reasoning-visibility.tsindex 33d0d3fbb3f..33d4f708011 100644--- a/studio/frontend/src/features/chat/utils/reasoning-visibility.ts+++ b/studio/frontend/src/features/chat/utils/reasoning-visibility.ts@@ -44,28 +44,3 @@ export function startsNewReasoningRound(): boolean {return isStreaming && !wasStreaming;}--export interface ReasoningToggleResult {- /** The user's choice for this block, kept until the round restarts or the setting changes. */- override: boolean;- /** Drop the streaming height cap so a hand-opened block shows in full. */- releaseStreamingHeight: boolean;-}--/** Resolves a trigger click into the next open state. Every click records an override, which is- * what keeps a hand-opened block open once its stream ends. */-export function resolveReasoningToggle(- open: boolean,- {- isStreaming,- visibility,- }: Pick<ReasoningOpenStateInput, "isStreaming" | "visibility">,-): ReasoningToggleResult {- return {- override: open,- // A block that opened on its own keeps the streaming cap. One opened against the setting- // is there to be read, so it gets its full height.- releaseStreamingHeight:- open && !defaultOpenFor(visibility, isStreaming),- };-}diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex 2bd16031d64..aa06f95ad0b 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -2853,6 +2853,50 @@ html[data-chat-font] .aui-root {}/* Flatten code blocks: single border, language label, then code directly */+ /* Reasoning fence fragments form one continuous surface. Interior fragments have+ no padding, border, or rounding at their seams. */+ .aui-reasoning-code-fragment {+ padding-inline: calc(1rem * var(--ui-space-scale, 1));+ background: var(--color-background);+ border-inline: 1px solid var(--color-border);+ font-size: calc(0.8125rem * var(--ui-font-scale, 1));+ line-height: 1.55;+ }+ .aui-reasoning-code-first {+ margin-top: calc(1rem * var(--ui-space-scale, 1));+ border-top: 1px solid var(--color-border);+ padding-top: calc(0.75rem * var(--ui-space-scale, 1));+ border-radius: 1.5rem 1.5rem 0 0;+ }+ .aui-reasoning-code-last {+ border-bottom: 1px solid var(--color-border);+ padding-bottom: calc(0.75rem * var(--ui-space-scale, 1));+ border-bottom-left-radius: 1.5rem;+ border-bottom-right-radius: 1.5rem;+ }+ .aui-reasoning-code-fragment pre,+ .aui-reasoning-code-fragment code {+ font-family: var(--custom-code-font, "Fira Code", ui-monospace, monospace);+ }+ .dark .aui-reasoning-code-fragment {+ background: var(--color-code-block);+ }+ .aui-reasoning-code-fragment code > span::before {+ display: none !important;+ }+ .aui-reasoning-prose-fragment > div > :first-child {+ margin-top: 0;+ }+ li[data-reasoning-list-continuation] {+ list-style-type: none;+ }+ .aui-reasoning-prose-fragment[data-table-continuation] thead {+ display: none;+ }+ [data-reasoning-fragment][data-index="0"] > .aui-reasoning-prose-fragment {+ padding-top: 0;+ }+[data-streamdown="code-block-body"] {border: none !important;border-radius: 0 !important;diff --git a/studio/frontend/tests/code-fence-body.test.ts b/studio/frontend/tests/code-fence-body.test.tsindex 501664626f8..aaeebb1693c 100644--- a/studio/frontend/tests/code-fence-body.test.ts+++ b/studio/frontend/tests/code-fence-body.test.ts@@ -49,7 +49,7 @@ test("a blank line is one line tall, not nothing", () => {assert.equal(isBlankLine([{ content: " " }]), false);assert.equal(isBlankLine([{ content: "" }, { content: "" }]), false);assert.ok(- /if \(isBlankLine\(line\)\) \{\s*return <span className=\{LINE_CLASS\}>\{"\\n"\}<\/span>;/+ /if \(!inline && isBlankLine\(line\)\) \{\s*return <span className=\{LINE_CLASS\}>\{"\\n"\}<\/span>;/.test(DEFER),"a blank line must render the newline streamdown renders for it",);diff --git a/studio/frontend/tests/reasoning-collapse-preference.test.ts b/studio/frontend/tests/reasoning-collapse-preference.test.tsindex 3e4e87f38d5..b2c0cacd4f3 100644--- a/studio/frontend/tests/reasoning-collapse-preference.test.ts+++ b/studio/frontend/tests/reasoning-collapse-preference.test.ts@@ -16,7 +16,6 @@ const { DISPLAY_VISIBILITIES } = await import(const {reasoningFollowsPreference,resolveReasoningOpen,- resolveReasoningToggle,startsNewReasoningRound,} = await import("../src/features/chat/utils/reasoning-visibility.ts");@@ -28,7 +27,7 @@ interface BlockState {// Mirrors the component: toggle results feed straight back into the open state.function applyToggle(state: BlockState, open: boolean): BlockState {- return { ...state, override: resolveReasoningToggle(open, state).override };+ return { ...state, override: open };}// Mirrors the component's render-time reset when the setting moves.@@ -168,33 +167,3 @@ test("regenerating drops the previous round's override", () => {state = { ...state, override: null };assert.equal(resolveReasoningOpen(state), false);});--test("streaming height cap is released only for a block opened against the setting", () => {- assert.equal(- resolveReasoningToggle(true, { isStreaming: true, visibility: "collapsed" })- .releaseStreamingHeight,- true,- );- // Re-opening a block that opened itself keeps the cap, so live text stays scrolled.- assert.equal(- resolveReasoningToggle(true, { isStreaming: true, visibility: "auto" })- .releaseStreamingHeight,- false,- );- assert.equal(- resolveReasoningToggle(true, { isStreaming: true, visibility: "expanded" })- .releaseStreamingHeight,- false,- );- // Opening a finished block that auto would have left closed still needs its full height.- assert.equal(- resolveReasoningToggle(true, { isStreaming: false, visibility: "auto" })- .releaseStreamingHeight,- true,- );- assert.equal(- resolveReasoningToggle(false, { isStreaming: false, visibility: "auto" })- .releaseStreamingHeight,- false,- );-});diff --git a/studio/frontend/tests/reasoning-document-pagination.test.ts b/studio/frontend/tests/reasoning-document-pagination.test.tsdeleted file mode 100644index e8005a0be99..00000000000--- a/studio/frontend/tests/reasoning-document-pagination.test.ts+++ /dev/null@@ -1,98 +0,0 @@-// 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 { fromMarkdown } from "mdast-util-from-markdown";-import { ReasoningPageSelector } from "../src/components/assistant-ui/reasoning-pagination.ts";-import { openWebUIRecordToConversation } from "../src/features/chat/utils/openwebui-import.ts";--test("imported consecutive reasoning documents retain their Markdown boundaries", () => {- const first = "Earlier analysis.\n\n".repeat(1200) + "BOUNDARY PARAGRAPH";- const second = "---\n\nINDEPENDENT DOCUMENT";- const conversation = openWebUIRecordToConversation(- {- chat: {- messages: [- {- id: "assistant",- role: "assistant",- content: "",- output: [- {- type: "reasoning",- summary: [{ type: "summary_text", text: first }],- },- {- type: "reasoning",- summary: [{ type: "summary_text", text: second }],- },- ],- },- ],- },- },- "reasoning boundaries",- );- assert.ok(conversation);- const parts = conversation.messages[0].content as {- type: string;- text: string;- }[];- const documents = parts- .filter((part) => part.type === "reasoning")- .map((part) => part.text);- assert.deepEqual(documents, [first, second]);-- const selector = new ReasoningPageSelector();- const latest = selector.selectDocument(documents);- assert.equal(latest.markdown, second);- assert.equal(latest.documentIndex, 1);- assert.equal(fromMarkdown(latest.markdown).children[0].type, "thematicBreak");- const earlier = selector.selectDocument(documents, { end: latest.start });- assert.equal(earlier.documentIndex, 0);- assert.equal(- fromMarkdown(earlier.markdown).children.at(-1)?.type,- "paragraph",- );- assert.ok(earlier.markdown.endsWith("BOUNDARY PARAGRAPH"));-});--test("document pagination preserves all source bytes and isolates open fences", () => {- const documents = [- "```text\n" + "code row\n".repeat(3000),- "# A separate thought\n",- "",- "More analysis.\n\n".repeat(1400),- ];- const selector = new ReasoningPageSelector();- const pages = [selector.selectDocument(documents)];- while (pages.at(-1)!.hasEarlier) {- pages.push(- selector.selectDocument(documents, { end: pages.at(-1)!.start }),- );- }- assert.equal(- pages- .reverse()- .map((page) => page.markdown)- .join(""),- documents.join(""),- );- assert.ok(pages.every((page) => page.markdown.length <= 8192));- const heading = pages.find((page) => page.documentIndex === 1)!;- assert.equal(heading.oversizedCode, false);- assert.equal(fromMarkdown(heading.markdown).children[0].type, "heading");-});--test("streaming a new document resets the prior document's live page start", () => {- const documents = ["first line\n".repeat(3000)];- const selector = new ReasoningPageSelector();- selector.selectDocument(documents, { streaming: true });- documents.push("A new independent thought.");- const page = selector.selectDocument(documents, { streaming: true });- assert.equal(page.markdown, documents[1]);- assert.equal(page.start, documents[0].length);- assert.equal(page.hasNewer, false);- assert.equal(page.hasEarlier, true);-});diff --git a/studio/frontend/tests/reasoning-grid-collapse.test.ts b/studio/frontend/tests/reasoning-grid-collapse.test.tsindex dc935c89ac7..0302c08fe5c 100644--- a/studio/frontend/tests/reasoning-grid-collapse.test.ts+++ b/studio/frontend/tests/reasoning-grid-collapse.test.ts@@ -141,27 +141,14 @@ test("the flag is on", () => {test("the reasoning pane picks its primitive from the flag on all three slots", () => {const code = codeOf(REASONING);- // Three primitive slots, plus the streaming-height release and the scroll lock, which both- // have to outlast the transition rather than the nominal duration.- assert.equal(code.match(/GRID_COLLAPSE_REASONING_ENABLED/g)?.length, 6);+ // Three primitive slots, the import, and the scroll lock that outlasts the transition.+ assert.equal(code.match(/GRID_COLLAPSE_REASONING_ENABLED/g)?.length, 5);assert.ok(code.includes("<UnmeasuredCollapsible {...rootProps}>"));assert.ok(code.includes("<Collapsible {...rootProps}>"));assert.ok(code.includes("UnmeasuredCollapsibleTrigger"));assert.ok(code.includes("<UnmeasuredCollapsibleContent"));});-test("the streaming height cap outlives the grid collapse, but only on the grid path", () => {- const code = codeOf(REASONING);- // `1fr` resolves against live content every frame, so releasing `max-h-64` before the row has- // finished shrinking grows it mid-collapse -- the jump the retention timer exists to prevent.- // The height keyframes animate a height captured at toggle time, so the default path is immune- // and must keep its exact ANIMATION_DURATION.- assert.ok(- code.includes("ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS"),- );- assert.ok(code.includes("const closeDelay = GRID_COLLAPSE_REASONING_ENABLED"));-});-test("the scroll lock outlasts the grid collapse, and the shared hook's other callers do not move", () => {const code = codeOf(REASONING);// The lock is armed in the click handler, a commit before the transition starts, so an exactdiff --git a/studio/frontend/tests/reasoning-highlight.test.ts b/studio/frontend/tests/reasoning-highlight.test.tsnew file mode 100644index 00000000000..7948f98d398--- /dev/null+++ b/studio/frontend/tests/reasoning-highlight.test.ts@@ -0,0 +1,55 @@+// 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 {+ reasoningHighlightReply,+ reasoningHighlightSource,+} from "../src/components/assistant-ui/reasoning-highlight.ts";++test("worker sources accept ordered deltas, viewport-only requests, and resets", () => {+ let source = reasoningHighlightSource("", "const bird = ");+ source = reasoningHighlightSource(source, {+ from: source.length,+ text: "true;",+ });+ assert.equal(source, "const bird = true;");+ assert.equal(+ reasoningHighlightSource(source, { from: source.length, text: "" }),+ source,+ );+ assert.equal(reasoningHighlightSource(source, "new source"), "new source");+});++test("highlighting transfers only requested lines, preserving grammar tokens", () => {+ const tokens = Array.from({ length: 10000 }, (_, i) => [+ { content: `line ${i}`, color: "red", offset: i },+ ]);+ const reply = reasoningHighlightReply(+ {+ client: 1,+ revision: 8,+ source: "unused",+ language: "js",+ lines: [4, 9999, 10000],+ },+ { tokens },+ );+ assert.deepEqual(+ reply.lines.map((line) => line.line),+ [4, 9999],+ );+ assert.equal(reply.lines[1].tokens, tokens[9999]);+ assert.equal(reply.revision, 8);+});++test("unavailable grammar produces no stale highlighted lines", () => {+ assert.deepEqual(+ reasoningHighlightReply(+ { client: 3, revision: 4, source: "code", language: null, lines: [0] },+ null,+ ),+ { client: 3, revision: 4, lines: [] },+ );+});diff --git a/studio/frontend/tests/reasoning-pagination.test.ts b/studio/frontend/tests/reasoning-pagination.test.tsdeleted file mode 100644index 6c3021f4e62..00000000000--- a/studio/frontend/tests/reasoning-pagination.test.ts+++ /dev/null@@ -1,251 +0,0 @@-// 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 {- REASONING_PAGE_CHARACTERS,- REASONING_PAGINATION_THRESHOLD,- ReasoningPageSelector,- createReasoningPageBoundary,- isReasoningPageBoundaryValid,- selectReasoningPage,- shouldPaginateReasoning,-} from "../src/components/assistant-ui/reasoning-pagination.ts";--const longReasoning = Array.from(- { length: 2_000 },- (_, index) => `paragraph ${index}: ${"reasoning ".repeat(8)}\n`,-).join("\n");--test("ordinary short reasoning is unchanged and does not paginate", () => {- const markdown = "# Thought\n\nA short explanation with `code`.";- const page = selectReasoningPage(markdown);-- assert.equal(shouldPaginateReasoning(markdown), false);- assert.deepEqual(page, {- end: markdown.length,- hasEarlier: false,- hasNewer: false,- markdown,- oversizedCode: false,- start: 0,- });- assert.equal(- shouldPaginateReasoning("x".repeat(REASONING_PAGINATION_THRESHOLD)),- false,- );- assert.equal(- shouldPaginateReasoning("x".repeat(REASONING_PAGINATION_THRESHOLD + 1)),- true,- );-});--test("long reasoning mounts one bounded page and navigation loses no source", () => {- const newestFirst = [selectReasoningPage(longReasoning)];- while (newestFirst.at(-1)?.hasEarlier) {- newestFirst.push(- selectReasoningPage(longReasoning, {- end: newestFirst.at(-1)?.start,- }),- );- }- const pages = newestFirst.reverse();-- assert.ok(pages.length > 10);- assert.ok(- pages.every((page) => page.markdown.length <= REASONING_PAGE_CHARACTERS),- );- assert.equal(pages.map((page) => page.markdown).join(""), longReasoning);- assert.equal(pages[0].hasEarlier, false);- assert.equal(pages.at(-1)?.hasNewer, false);- assert.ok(pages.slice(0, -1).every((page) => page.hasNewer));-});--test("an earlier page and its boundary stay stable while the live tail grows", () => {- const latest = selectReasoningPage(longReasoning);- const boundary = createReasoningPageBoundary(longReasoning, latest.start);- const earlier = selectReasoningPage(longReasoning, { end: boundary.end });- const appended = `${longReasoning}\nnew streamed tokens`;-- assert.equal(isReasoningPageBoundaryValid(appended, boundary), true);- assert.deepEqual(- selectReasoningPage(appended, { end: boundary.end }),- earlier,- );-- const rewritten = `${longReasoning.slice(0, boundary.end - 2)}XX${longReasoning.slice(boundary.end)}`;- assert.equal(isReasoningPageBoundaryValid(rewritten, boundary), false);-});--test("giant closed and open fences use bounded visibly-safe fallback pages", () => {- for (const markdown of [- `\`\`\`typescript\n${"const value = 1;\n".repeat(2_000)}\`\`\`\n`,- `~~~python\n${"print('streaming')\n".repeat(2_000)}`,- ]) {- const latest = selectReasoningPage(markdown);- const earlier = selectReasoningPage(markdown, { end: latest.start });-- for (const page of [latest, earlier]) {- assert.ok(page.markdown.length <= REASONING_PAGE_CHARACTERS);- assert.equal(page.oversizedCode, true);- }- }-});--test("the streaming selector incrementally tracks append and resets on replacement", () => {- const selector = new ReasoningPageSelector();- const openFence = `prefix\n\n~~~ts\n${"const x = 1;\n".repeat(1_000)}`;- const appended = `${openFence}~~~\n\nlatest paragraph\n`;-- assert.deepEqual(selector.select(openFence), selectReasoningPage(openFence));- assert.deepEqual(selector.select(appended), selectReasoningPage(appended));- assert.deepEqual(- selector.select(longReasoning),- selectReasoningPage(longReasoning),- );-});-test("live pages advance in stable half-page strides", () => {- const selector = new ReasoningPageSelector();- const maxCharacters = 4_096;- let markdown = longReasoning.slice(0, 20_000);- const first = selector.select(markdown, { maxCharacters, streaming: true });-- markdown += "streamed tail ".repeat(500);- const advanced = selector.select(markdown, {- maxCharacters,- streaming: true,- });- const room = maxCharacters - advanced.markdown.length;- assert.ok(advanced.start > first.start);- assert.ok(room > 100);-- markdown += "x".repeat(Math.floor(room / 2));- const stable = selector.select(markdown, { maxCharacters, streaming: true });- assert.equal(stable.start, advanced.start);- assert.ok(stable.markdown.length <= maxCharacters);-- markdown += "y".repeat(room);- const nextStride = selector.select(markdown, {- maxCharacters,- streaming: true,- });- assert.ok(nextStride.start > stable.start);- assert.ok(nextStride.markdown.length <= maxCharacters);-});--test("same-edge equal-length replacement resets incremental fence state", () => {- const selector = new ReasoningPageSelector();- const edge = "edge".repeat(512);- const fence = `\n\`\`\`ts\n${"const stale = true;\n".repeat(600)}\`\`\`\n`;- const oldSource = edge + fence + edge;- const replacement = edge + " ".repeat(fence.length) + edge;-- assert.equal(- selector.select(oldSource, { maxCharacters: 4_096 }).oversizedCode,- true,- );- assert.deepEqual(- selector.select(replacement, { maxCharacters: 4_096 }),- selectReasoningPage(replacement, { maxCharacters: 4_096 }),- );- assert.equal(- selector.select(replacement, { maxCharacters: 4_096 }).oversizedCode,- false,- );-});--test("CRLF bytes and unicode survive complete pagination", () => {- const markdown = Array.from(- { length: 1_500 },- (_, index) => `row ${index}: 😀 café`,- ).join("\r\n");- const newestFirst = [selectReasoningPage(markdown, { maxCharacters: 1_024 })];- while (newestFirst.at(-1)?.hasEarlier) {- newestFirst.push(- selectReasoningPage(markdown, {- end: newestFirst.at(-1)?.start,- maxCharacters: 1_024,- }),- );- }- const rebuilt = newestFirst- .reverse()- .map((page) => page.markdown)- .join("");-- assert.equal(rebuilt, markdown);- assert.equal(rebuilt.includes("\r\n"), true);- assert.equal(rebuilt.includes("😀"), true);- assert.equal(rebuilt.includes("\uFFFD"), false);-});--test("a small page budget still yields a page that holds characters", () => {- // Shrunk from a fuzz failure and kept verbatim: the trigger is a separator- // sitting immediately before `end`. `pageStart` searches FORWARD from its- // target and returns the offset just after the separator, which could reach- // `end` itself whenever the search window was allowed to extend that far --- // that is, whenever `maxCharacters <= BOUNDARY_SEARCH_CHARACTERS` (1,024).- //- // The invariant, as a sentence: a page start must stay STRICTLY BELOW the- // page end, because `Earlier` sets the next page's end to this start. A start- // equal to `end` yields an empty page whose own start is that same offset, so- // the chain stops advancing and everything before it is unreachable by paging.- const markdown = `${"x".repeat(4_000)}\n${"y".repeat(4_000)}\n`;-- for (const maxCharacters of [64, 256, 1_023, 1_024, 1_025, 2_048]) {- const page = selectReasoningPage(markdown, {- end: markdown.length,- maxCharacters,- });- assert.ok(- page.start < page.end,- `start ${page.start} must stay below end ${page.end} at maxCharacters ${maxCharacters}`,- );- assert.equal(page.markdown.length, page.end - page.start);- assert.ok(page.markdown.length > 0);- }-});--test("the Earlier chain rebuilds the whole trace at every page budget", () => {- // The property the feature rests on: paging backwards loses nothing. Run at- // budgets on both sides of BOUNDARY_SEARCH_CHARACTERS, because the bug above- // was invisible at the shipped 8,192 default and only appeared below it.- const markdown = `${longReasoning}\n\`\`\`py\n${"c = 1\n".repeat(400)}\`\`\`\n${longReasoning}`;-- for (const maxCharacters of [128, 1_024, 4_096, REASONING_PAGE_CHARACTERS]) {- const pages: string[] = [];- let end: number | null = null;- for (let step = 0; step < 5_000; step += 1) {- const page = selectReasoningPage(markdown, { end, maxCharacters });- assert.ok(page.start < page.end || page.end === 0);- pages.push(page.markdown);- if (!page.hasEarlier || page.start === 0) {- break;- }- end = page.start;- }- assert.equal(pages.reverse().join(""), markdown);- }-});--test("a page budget shorter than a surrogate pair keeps the character whole", () => {- const markdown = `${"a".repeat(200)}\n\u{1F600}`;- const page = selectReasoningPage(markdown, {- end: markdown.length,- maxCharacters: 1,- });-- assert.ok(page.markdown.length > 0);- // Never a lone half: the page carries the whole astral character or none of- // it. Iterating a string yields code POINTS, so a surviving lone surrogate- // shows up here as a single unit still inside the surrogate range.- for (const codePoint of page.markdown) {- const value = codePoint.codePointAt(0) ?? 0;- assert.ok(- value < 0xd800 || value > 0xdfff,- `page opened on a lone surrogate (U+${value.toString(16)})`,- );- }-});diff --git a/studio/frontend/tests/reasoning-transcript-index.test.ts b/studio/frontend/tests/reasoning-transcript-index.test.tsnew file mode 100644index 00000000000..7a72c6f1f51--- /dev/null+++ b/studio/frontend/tests/reasoning-transcript-index.test.ts@@ -0,0 +1,408 @@+// 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 { fromMarkdown } from "mdast-util-from-markdown";+import remend from "remend";+import { gfm } from "micromark-extension-gfm";+import { gfmFromMarkdown } from "mdast-util-gfm";+import {+ ReasoningTranscriptIndex,+ findReasoningAnchor,+ REASONING_FRAGMENT_CHARACTERS,+} from "../src/components/assistant-ui/reasoning-transcript-index.ts";++test("reading anchors resolve rendered Markdown, not formatting delimiters", () => {+ const fragments = new ReasoningTranscriptIndex().update([+ "Before\n\nA **bold** thought.\n\nAfter",+ ]);+ assert.equal(findReasoningAnchor(fragments, "A bold thought."), 1);+ assert.equal(findReasoningAnchor(fragments, "Missing"), -1);+});++test("long prose remains lossless and completed fragments keep their identity", () => {+ const index = new ReasoningTranscriptIndex();+ const source = Array.from(+ { length: 1000 },+ (_, i) => `Paragraph ${i}: **thoughts** about the game.\n\n`,+ ).join("");+ const before = index.update([source]);+ assert.equal(before.map((part) => part.text).join(""), source);+ assert.ok(+ before.every((part) => part.text.length <= REASONING_FRAGMENT_CHARACTERS),+ );+ const after = index.update([source + "Another thought"]);+ assert.equal(after[0], before[0]);+ assert.equal(after[0].key, before[0].key);+ assert.equal(+ after.map((part) => part.text).join(""),+ source + "Another thought",+ );+});++test("a giant fence does not swallow the surrounding prose", () => {+ const body = Array.from(+ { length: 5000 },+ (_, i) => `const bird${i} = ${i};`,+ ).join("\n");+ const source = `**Before**\n\n\`\`\`javascript\n${body}\n\`\`\`\n\n**After**`;+ const rows = new ReasoningTranscriptIndex().update([source]);+ assert.equal(rows[0].code, undefined);+ assert.equal(rows.at(-1)!.code, undefined);+ assert.match(rows.at(-1)!.text, /\*\*After\*\*/);+ const code = rows.filter((row) => row.code);+ assert.ok(code.length > 100);+ assert.equal(+ code.flatMap((row) => row.code!.lines.map((line) => line.text)).join("\n"),+ body,+ );+ assert.ok(+ code.every(+ (row) => row.code!.source === body && row.code!.language === "javascript",+ ),+ );+ assert.equal(code.filter((row) => row.first).length, 1);+ assert.equal(code.filter((row) => row.last).length, 1);+});++test("streaming fences retain completed rows and normalize only their pending tail", () => {+ const index = new ReasoningTranscriptIndex();+ let body = "const bird = 1;\r\n".repeat(10000);+ const rows = index.update(["```js\r\n" + body]);+ for (let i = 0; i < 100; i += 1) {+ body += `const bird${i} = ${i};\r\n`;+ const next = index.update(["```js\r\n" + body]);+ assert.equal(next[0], rows[0]);+ assert.equal(next[500], rows[500]);+ assert.equal(+ next[0].code!.source,+ body.replace(/\r\n/g, "\n").replace(/\n$/, ""),+ );+ }+});++test("incremental fence text matches Markdown indentation, CRLF, and closing semantics", () => {+ for (const indent of ["", " ", " "]) {+ const source =+ indent ++ "~~~js\r\n" ++ (indent + "\tconst bird = '😀';\r\n").repeat(1000) ++ "\r\n" ++ indent ++ "~~~\n";+ const index = new ReasoningTranscriptIndex();+ for (let end = 100; end < source.length; end += 257) {+ const part = source.slice(0, end);+ const expected = fromMarkdown(part).children[0];+ const rows = index.update([part]);+ const bounded = fromMarkdown(rows[0].text).children[0];+ assert.equal(+ rows[0].code?.source ??+ (bounded.type === "code" ? bounded.value.replace(/\r\n/g, "\n") : ""),+ expected.type === "code"+ ? expected.value.replace(/\r\n/g, "\n")+ : "not code",+ );+ }+ const expected = fromMarkdown(source).children[0];+ assert.equal(+ index.update([source])[0].code!.source,+ expected.type === "code"+ ? expected.value.replace(/\r\n/g, "\n")+ : "not code",+ );+ }+});++test("bounded mermaid fences retain their specialized renderer while streaming", () => {+ const index = new ReasoningTranscriptIndex();+ const prefix = "Earlier thought.\n\n".repeat(1000);+ const first = index.update([prefix + "```mermaid\ngraph TD\nA"]);+ assert.equal(first.at(-1)!.code, undefined);+ const next = index.update([prefix + "```mermaid\ngraph TD\nA-->B\n```"]);+ assert.equal(next.at(-1)!.code, undefined);+ assert.match(next.at(-1)!.text, /A-->B/);+});++test("bounded SVG fences retain the existing sanitized preview renderer", () => {+ for (const language of ["svg", "SVG", "xml", "html"]) {+ const svg = `\`\`\`${language}\n<svg xmlns="http://www.w3.org/2000/svg"><circle r="10"/></svg>\n\`\`\``;+ const rows = new ReasoningTranscriptIndex().update([+ "Earlier thought.\n\n".repeat(1000) + svg,+ ]);+ assert.equal(rows.at(-1)!.code, undefined);+ assert.equal(rows.at(-1)!.text, svg);+ }+});++test("bounded HTML documents retain the established artifact renderer", () => {+ const html = "```html\n<!doctype html><html><body>Game</body></html>\n```";+ const rows = new ReasoningTranscriptIndex().update([+ "Earlier thought.\n\n".repeat(1000) + html,+ ]);+ assert.equal(rows.at(-1)!.code, undefined);+ assert.equal(rows.at(-1)!.text, html);+});++test("large fence completion follows its delimiter, not later streaming prose", () => {+ const index = new ReasoningTranscriptIndex();+ const open = "```js\n" + "const bird = true;\n".repeat(1000);+ const first = index.update([open])[0];+ assert.equal(first.code!.incomplete, true);+ for (const [suffix, incomplete] of [+ ["`", true],+ ["``", true],+ ["```", false],+ ["```x", true],+ ["```x\n```", false],+ ["```x\n```\n\nLater thought", false],+ ] as const) {+ const rows = index.update([open + suffix]);+ assert.equal(rows[0], first);+ assert.equal(first.code!.incomplete, incomplete);+ }+});++test("large tables retain headers and alignment as render-only continuation context", () => {+ const source =+ "| Item | Value |\n| :--- | ---: |\n" + "| bird | 42 |\n".repeat(3000);+ const rows = new ReasoningTranscriptIndex().update([source]);+ assert.equal(rows.map((row) => row.text).join(""), source);+ for (const [i, row] of rows.entries()) {+ const table = fromMarkdown(row.renderText ?? row.text, {+ extensions: [gfm()],+ mdastExtensions: [gfmFromMarkdown()],+ }).children[0];+ assert.equal(table.type, "table");+ assert.equal(Boolean(row.tableContinuation), i > 0);+ }+});++test("definition-only fragments do not create visible spacing rows", () => {+ const rows = new ReasoningTranscriptIndex().update([+ "Before\n\n[a]: https://a.org\n\n[b]: https://b.org\n\nAfter",+ ]);+ assert.deepEqual(+ rows.map((row) => Boolean(row.hidden)),+ [false, true, true, false],+ );+});++test("fence grammar and independent document boundaries survive streaming", () => {+ const index = new ReasoningTranscriptIndex();+ const open = "````html\n<div>\n```example\n" + "code\n".repeat(5000);+ const before = index.update([open, "# Another document"]);+ assert.equal(before.at(-1)!.text, "# Another document");+ assert.equal(before.at(-1)!.code, undefined);+ const after = index.update([+ open + "</div>\n````\n\nNormal **prose**",+ "# Another document",+ ]);+ assert.equal(after[0].key, before[0].key);+ assert.ok(+ after.some((row) => !row.code && row.text.includes("Normal **prose**")),+ );+ assert.ok(+ after+ .filter((row) => row.code)+ .every((row) => row.code!.source.includes("```example")),+ );+});++test("replacement and truncation discard stale fragments", () => {+ const index = new ReasoningTranscriptIndex();+ const old = index.update(["old thoughts\n\n".repeat(2000)]);+ const next = index.update(["New **thought**"]);+ assert.equal(next.length, 1);+ assert.equal(next[0].text, "New **thought**");+ assert.notEqual(next[0].key, old[0].key);+ assert.deepEqual(index.update([""]), []);+});++test("long unbroken lines stay bounded without losing surrogate pairs or CRLF", () => {+ for (const text of [+ "a😀".repeat(10000),+ "word\r\n".repeat(5000),+ "x".repeat(50000),+ "\n\n Leading whitespace\n\n" + "word ".repeat(5000),+ ]) {+ const rows = new ReasoningTranscriptIndex().update([text]);+ assert.equal(rows.map((row) => row.text).join(""), text);+ assert.ok(+ rows.every((row) => row.text.length <= REASONING_FRAGMENT_CHARACTERS),+ );+ assert.ok(rows.every((row) => !/[\uD800-\uDBFF]$/.test(row.text)));+ }+});++test("an enormous code line is fragmented, including when the language is unknown", () => {+ const source = "x😀".repeat(50000);+ const rows = new ReasoningTranscriptIndex().update([+ "~~~unknown\n" + source + "\n~~~",+ ]);+ assert.ok(+ rows.every(+ (row) => row.code && row.text.length <= REASONING_FRAGMENT_CHARACTERS,+ ),+ );+ assert.equal(rows.map((row) => row.text).join(""), source);+});++test("a closing delimiter split across appends cannot eat later prose", () => {+ const index = new ReasoningTranscriptIndex();+ for (const suffix of ["`", "``", "```", "```\n", "```\n\nAfter"]) {+ const rows = index.update(["```js\nconst bird = true;\n" + suffix]);+ if (suffix.endsWith("After"))+ assert.ok(rows.some((row) => !row.code && row.text.includes("After")));+ else assert.ok(rows[0].code);+ }+});++test("a bold paragraph keeps its formatting across bounded continuations", () => {+ const text = "**" + "long thought ".repeat(3000).trimEnd() + "**";+ const rows = new ReasoningTranscriptIndex().update([text]);+ assert.equal(rows.map((row) => row.text).join(""), text);+ for (const row of rows) {+ const parsed = fromMarkdown(remend(row.renderText ?? row.text));+ assert.equal(parsed.children[0].type, "paragraph");+ const paragraph = parsed.children[0];+ assert.ok(+ "children" in paragraph &&+ paragraph.children.some((child) => child.type === "strong"),+ );+ }+});++test("a quoted fence remains code when it crosses a rendering boundary", () => {+ const text =+ "> ```python\n" + "> print('bird')\n".repeat(3000) + "> ```\n\nAfter";+ const rows = new ReasoningTranscriptIndex().update([text]);+ assert.equal(rows.map((row) => row.text).join(""), text);+ for (const row of rows.filter((part) =>+ part.text.includes("print('bird')"),+ )) {+ const parsed = fromMarkdown(row.renderText ?? row.text);+ const quote = parsed.children[0];+ assert.equal(quote.type, "blockquote");+ assert.ok(+ "children" in quote &&+ quote.children.some((child) => child.type === "code"),+ );+ }+ assert.match(rows.at(-1)!.text, /After/);+});++test("reference links retain document definitions across fragments and appends", () => {+ const index = new ReasoningTranscriptIndex();+ const source = "Earlier paragraph.\n\n".repeat(1000) + "[Link][Ref]\n\n";+ const before = index.update([source]);+ const complete = source + '[ref]: https://example.org "Title"\n\nDone';+ const rows = index.update([complete]);+ assert.equal(rows.map((row) => row.text).join(""), complete);+ assert.equal(rows[0], before[0]);+ const link = rows.find((row) => row.text.includes("[Link]"))!;+ const parsed = fromMarkdown(link.renderText ?? link.text);+ assert.ok(parsed.children.some((node) => node.type === "paragraph"));+ assert.ok(JSON.stringify(parsed).includes('"type":"linkReference"'));+ assert.ok(JSON.stringify(parsed).includes('"url":"https://example.org"'));+ assert.equal(rows[0].renderText, undefined);+ const independent = index.update([complete, "[Link][ref]"]);+ assert.equal(independent.at(-1)!.renderText, undefined);+});++test("reference definitions update pending URLs, honor first wins, and reset", () => {+ const index = new ReasoningTranscriptIndex();+ const source = "[ref]\n\n[ref]: https://example.org";+ const row = () => index.update([source])[0];+ assert.match(row().renderText!, /https:\/\/example.org/);+ const updated = index.update([+ source + "/page\n\n[ref]: https://ignored.org",+ ]);+ assert.match(updated[0].renderText!, /https:\/\/example.org\/page/);+ assert.doesNotMatch(updated[0].renderText!, /ignored/);+ assert.equal(+ index.update(["[ref]\n\nNo definition"])[0].renderText,+ undefined,+ );+});++test("definitions inside quotes and lists retain document-wide scope", () => {+ for (const definition of [+ "> [ref]: https://example.org",+ "- [ref]: https://example.org",+ '> [ref]:\n> https://example.org\n> "Title"',+ ]) {+ const rows = new ReasoningTranscriptIndex().update([+ "[Link][ref]\n\nEarlier paragraph.\n\n" + definition,+ ]);+ const parsed = fromMarkdown(rows[0].renderText ?? rows[0].text);+ assert.ok(JSON.stringify(parsed).includes('"type":"linkReference"'));+ assert.ok(JSON.stringify(parsed).includes('"url":"https://example.org"'));+ }+});++test("synthesized definitions preserve entities and document-first precedence", () => {+ const rows = new ReasoningTranscriptIndex().update([+ '[Link][ref]\n\n[ref]: https://example.org/?x=&amp; "&amp;"',+ ]);+ const definition = fromMarkdown(rows[0].renderText!).children.find(+ (node) => node.type === "definition",+ )!;+ assert.equal(definition.url, "https://example.org/?x=&");+ assert.equal(definition.title, "&");+ const duplicates = new ReasoningTranscriptIndex().update([+ "[ref]: https://first.org\n\n> [ref]: https://second.org\n>\n> [Link][ref]",+ ]);+ assert.match(+ duplicates.at(-1)!.renderText!,+ /^\[ref\]: <https:\/\/first.org>/,+ );+});++test("oversized quoted items keep their enclosing blockquote", () => {+ const source = "> 1. " + "Long item ".repeat(3000);+ const rows = new ReasoningTranscriptIndex().update([source]);+ assert.equal(rows.map((row) => row.text).join(""), source);+ for (const row of rows) {+ const node = fromMarkdown(row.renderText ?? row.text).children[0];+ assert.equal(node.type, "blockquote");+ if (node.type === "blockquote") assert.equal(node.children[0].type, "list");+ }+});++test("oversized ordered, unordered, and nested items retain list containers", () => {+ for (const marker of ["1. ", "7) ", "- ", "- Parent\n 1. "]) {+ const source = marker + "Long item ".repeat(3000) + "\n";+ const rows = new ReasoningTranscriptIndex().update([source]);+ assert.equal(rows.map((row) => row.text).join(""), source);+ for (const [i, row] of rows.entries()) {+ const parsed = fromMarkdown(row.renderText ?? row.text);+ assert.equal(parsed.children[0].type, "list", row.key);+ assert.equal(+ row.listContinuationDepth ?? 0,+ i === 0 ? 0 : marker.includes("Parent") ? 2 : 1,+ );+ assert.ok(row.text.length <= REASONING_FRAGMENT_CHARACTERS);+ }+ }+});++test("a list split between items does not invent a nested continuation", () => {+ const source = Array.from(+ { length: 2000 },+ (_, i) => `${i + 1}. Item ${i}\n`,+ ).join("");+ const rows = new ReasoningTranscriptIndex().update([source]);+ assert.equal(rows.map((row) => row.text).join(""), source);+ for (const row of rows) {+ const list = fromMarkdown(row.renderText ?? row.text).children[0];+ assert.equal(list.type, "list");+ if (list.type !== "list") continue;+ assert.equal(list.start, Number.parseInt(row.text));+ assert.equal(row.listContinuationDepth ?? 0, 0);+ assert.ok(+ list.children.every((item) => item.children[0].type === "paragraph"),+ );+ }+});diff --git a/studio/frontend/tests/reasoning-selection-pagination.test.ts b/studio/frontend/tests/reasoning-transcript-selection.test.tssimilarity index 89%rename from studio/frontend/tests/reasoning-selection-pagination.test.tsrename to studio/frontend/tests/reasoning-transcript-selection.test.tsindex 96ef4c6bd0b..16502a37f14 100644--- a/studio/frontend/tests/reasoning-selection-pagination.test.ts+++ b/studio/frontend/tests/reasoning-transcript-selection.test.ts@@ -13,7 +13,7 @@ const CONTENT_REF = /<ReasoningContent[\s\S]*?ref=\{reasoningContentRef\}/;const SCOPED_SELECTION_CHECK =/selectionIntersectsElement\(\s*window\.getSelection\(\),\s*reasoningContentRef\.current,?\s*\)/g;-test("pagination defers only for a selection intersecting this reasoning block", () => {+test("transcript activation defers only for a selection intersecting this reasoning block", () => {assert.match(REASONING, INTERSECTION_HELPER);assert.match(REASONING, CONTENT_REF);assert.equal(REASONING.match(SCOPED_SELECTION_CHECK)?.length, 2);diff --git a/studio/frontend/tests/thinking-fold.test.ts b/studio/frontend/tests/thinking-fold.test.tsindex 0e035140f94..d78d12d62c8 100644--- a/studio/frontend/tests/thinking-fold.test.ts+++ b/studio/frontend/tests/thinking-fold.test.ts@@ -282,7 +282,7 @@ test("opening by hand grows the block downward instead of pinning the bottom", (const reasoning = readSrc("components/assistant-ui/reasoning.tsx");assert.match(reasoning,- /if \(open && !isReasoningStreaming\) \{\n\s*detachFromBottom\(\);\n\s*\}/,+ /if \(open\) \{\n\s*detachFromBottom\(\);\n\s*\}/,);for (const file of ["tool-group.tsx", "tool-fallback.tsx"]) {const source = readSrc(`components/assistant-ui/${file}`);@@ -379,7 +379,7 @@ test("later thinking rounds render inside the lead, with no header of their own"reasoning.indexOf("const FoldedReasoningRound"),reasoning.indexOf("const ReasoningGroupBlock"),);- assert.match(foldedRound, /const pages = useReasoningPages\(/);+ assert.match(foldedRound, /const transcript = useReasoningTranscriptMode\(/);assert.match(foldedRound, /<ReasoningBody\n/);// Copy on the lead reaches the folded rounds, which have no Copy of their own.assert.match(diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.jsonindex 2d1ffbabfb4..a189a89b9b3 100644--- a/studio/frontend/tsconfig.app.json+++ b/studio/frontend/tsconfig.app.json@@ -42,6 +42,7 @@"smoke-shortcuts-main.tsx","smoke-stream-pacing-main.tsx","smoke-code-block-flicker-main.tsx",- "smoke-tool-activity-main.tsx"+ "smoke-tool-activity-main.tsx",+ "smoke-reasoning-transcript-main.tsx"]}diff --git a/studio/frontend/vite.config.ts b/studio/frontend/vite.config.tsindex ccd22278d28..f804b645def 100644--- a/studio/frontend/vite.config.ts+++ b/studio/frontend/vite.config.ts@@ -26,6 +26,8 @@ function smokeModuleDelay(): Plugin {// https://vite.dev/config/export default defineConfig({+ // Reasoning's highlighter loads only the grammar it needs in its module worker.+ worker: { format: "es" },plugins: [react(), tailwindcss(), smokeModuleDelay()],// Keep an unrelated PostCSS config in an ancestor directory from leaking// into Unsloth installs. Tailwind is provided by its dedicated Vite plugin.diff --git a/studio/frontend/vite.reasoning.config.ts b/studio/frontend/vite.reasoning.config.tsnew file mode 100644index 00000000000..86c5f75593d--- /dev/null+++ b/studio/frontend/vite.reasoning.config.ts@@ -0,0 +1,19 @@+// 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 path from "node:path";+import { mergeConfig } from "vite";+import base from "./vite.config";++export default mergeConfig(base, {+ build: {+ emptyOutDir: true,+ outDir: path.resolve(+ __dirname,+ "../../.playwright-cli/reasoning-production",+ ),+ rollupOptions: {+ input: path.resolve(__dirname, "smoke-reasoning-transcript.html"),+ },+ },+});diff --git a/tests/studio/playwright_thread_scoped_settings.py b/tests/studio/playwright_thread_scoped_settings.pyindex 448c0003292..b4d6c5ea1bb 100644--- a/tests/studio/playwright_thread_scoped_settings.py+++ b/tests/studio/playwright_thread_scoped_settings.py@@ -16,7 +16,6 @@ lets this run in seconds rather than behind a GGUF download.import jsonimport os-import reimport sysimport timeimport uuid@@ -303,14 +302,14 @@ def read_globals(page):)-def check_reasoning_page_navigation(page, token):- step("saved reasoning pages render the selected source range")+def check_reasoning_transcript(page, token):+ step("saved reasoning scrolls continuously with bounded content and full-source copy")source = "\n\n".join(f"Step {index:04d}. Compare this observation with the preceding reasoning ""and keep the complete trace available for inspection."for index in range(400))- thread_id = seed_thread(page, token, "Reasoning page navigation")+ thread_id = seed_thread(page, token, "Continuous reasoning transcript")messages = api(page, f"/api/chat/threads/{thread_id}/messages", token = token)["messages"]messages.append({@@ -337,32 +336,40 @@ def check_reasoning_page_navigation(page, token):# reworded the trigger to "Worked for ...", and a driver that names the copy fails the# whole leg on a wording change while the button it wants is right there. The slot is# what the component guarantees; the wording is product copy and moves.- page.locator('[data-slot="reasoning-trigger"]').first.click()- navigation = page.get_by_role("navigation", name = "Reasoning pages")+ trigger = page.locator('[data-slot="reasoning-trigger"]').first+ if trigger.get_attribute("data-state") == "open":+ trigger.click()+ expect(page.locator('[data-slot="reasoning-transcript"]')).to_have_count(0)+ trigger.click()body = page.locator('[data-slot="reasoning-text"]')-- def expect_selected_page():- expect(navigation).to_be_visible()- match = re.search(r"(\d+)–(\d+) of (\d+)", navigation.inner_text())- assert match, "missing reasoning source range"- start, end, total = map(int, match.groups())- assert total == len(source)- assert 0 < end - start + 1 <= 8192- expect(body).to_have_text(source[start - 1 : end].replace("\n", ""))- return start, end-- latest = expect_selected_page()- navigation.get_by_role("button", name = "Earlier", exact = True).click()- earlier = expect_selected_page()- assert earlier[1] < latest[0]- navigation.get_by_role("button", name = "Earlier", exact = True).click()- oldest = expect_selected_page()- assert oldest[1] < earlier[0]- navigation.get_by_role("button", name = "Newer", exact = True).click()- assert expect_selected_page() == earlier- navigation.get_by_role("button", name = "Latest", exact = True).click()- assert expect_selected_page() == latest+ transcript = page.locator('[data-slot="reasoning-transcript"]')+ expect(transcript).to_be_visible()+ expect(page.locator('[data-slot="reasoning-page-navigation"]')).to_have_count(0)+ expect(body).to_contain_text("Step 0000.")+ assert len(body.inner_text()) < 20000, "saved reasoning mounted the entire trace"++ page.context.grant_permissions(["clipboard-read", "clipboard-write"])+ page.get_by_role("button", name = "Copy reasoning", exact = True).click()+ expect(page.get_by_role("button", name = "Copied", exact = True)).to_be_visible()+ assert page.evaluate("navigator.clipboard.readText()") == source++ viewport = page.locator(".aui-thread-viewport")+ box = viewport.bounding_box()+ page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)+ page.mouse.wheel(0, 100000)+ expect(body).to_contain_text("Step 0399.")+ assert len(body.inner_text()) < 20000, "scrolling mounted the entire trace"expect(page.get_by_text("The final answer stays separate.", exact = True)).to_be_visible()+ expect(body).not_to_contain_text("The final answer stays separate.")++ trigger.click()+ expect(transcript).to_have_count(0)+ page.wait_for_timeout(300)+ header_top = trigger.bounding_box()["y"]+ trigger.click()+ expect(body).to_contain_text("Step 0000.")+ page.wait_for_timeout(300)+ assert abs(trigger.bounding_box()["y"] - header_top) < 3, "reopening moved the header"def main():@@ -521,7 +528,7 @@ def main():if thread.get("settings") is not None:fail(f"thread listing carries a settings snapshot: {thread['id']}")- check_reasoning_page_navigation(page, token)+ check_reasoning_transcript(page, token)if page_errors:fail(f"page errors during the run: {page_errors[:3]!r}")diff --git a/tests/studio/reasoning-codex-checks.js b/tests/studio/reasoning-codex-checks.jsnew file mode 100644index 00000000000..bef981868ca--- /dev/null+++ b/tests/studio/reasoning-codex-checks.js@@ -0,0 +1,150 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// playwright-cli run-code --filename=tests/studio/reasoning-codex-checks.js+async (page) => {+ const check = (condition, message) => { if (!condition) throw new Error(message); };+ await page.addInitScript(() => {+ localStorage.setItem("unsloth_chat_collapse_html_artifacts", "true");+ if (window.__fenceTransfers) return;+ window.__fenceTransfers = { full: [], delta: [] };+ const post = Worker.prototype.postMessage;+ Worker.prototype.postMessage = function (message, ...args) {+ if (typeof message.source === "string") window.__fenceTransfers.full.push(message.source.length);+ else if (message.source?.text !== undefined) window.__fenceTransfers.delta.push(message.source.text.length);+ return post.call(this, message, ...args);+ };+ });+ await page.reload();+ await page.setViewportSize({ width: 1280, height: 900 });+ await page.waitForFunction(() => window.__reasoning);+ await page.evaluate(() => window.__reasoning.run({ size: 250000, kind: "code", chunk: 512, gap: 12 }));+ await page.waitForFunction(() => window.__reasoning.stats().done, { timeout: 60000 });+ await page.waitForTimeout(400);+ const streaming = await page.evaluate(() => ({ ...window.__reasoning.stats(), transfers: window.__fenceTransfers }));+ check(streaming.mounted < 30000, "live code mounted unbounded content");+ check(streaming.transfers.delta.length > 20, "live fence did not use incremental worker transfers");+ check(streaming.transfers.full.length < 10, "live fence repeatedly transferred its complete history");++ const selectedCode = await page.evaluate(() => {+ const row = [...document.querySelectorAll("[data-reasoning-code-row]")].find((node) => {+ const rect = node.getBoundingClientRect(); return rect.top > 100 && rect.top < 600;+ });+ if (!row) throw new Error("no visible code row to select");+ const range = document.createRange(); range.selectNodeContents(row);+ const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);+ window.__codeSelectionAnchor = { node: selection.anchorNode, offset: selection.anchorOffset };+ return selection.toString();+ });+ await page.mouse.move(550, 350); await page.mouse.wheel(0, -7000);+ await page.waitForTimeout(500);+ check(await page.evaluate(() => getSelection().toString()) === selectedCode, "scrolling to earlier code destroyed native selection");+ await page.keyboard.down("Shift"); await page.mouse.click(500, 150); await page.keyboard.up("Shift");+ await page.waitForTimeout(300);+ check(await page.evaluate(() => {+ const selection = getSelection(), anchor = window.__codeSelectionAnchor;+ return selection.toString().length > 0 && selection.anchorNode === anchor.node && selection.anchorOffset === anchor.offset;+ }), "extending selection across a code gap lost its original endpoint");+ await page.evaluate(() => getSelection().removeAllRanges());++ await page.evaluate(() => window.__reasoning.seed({ text: "~~~text\n" + "x".repeat(25000) + "\n~~~" }));+ await page.mouse.move(550, 350); await page.mouse.wheel(0, 100000);+ await page.waitForTimeout(500);+ const selection = await page.evaluate(() => {+ const rows = [...document.querySelectorAll("[data-reasoning-code-row]")];+ const range = document.createRange();+ range.setStart(rows[0], 0); range.setEnd(rows[1], rows[1].childNodes.length);+ const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);+ const result = { text: selection.toString(), expected: rows[0].textContent + rows[1].textContent };+ const rectAt = (row, last) => {+ const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT);+ const texts = []; for (let n = walker.nextNode(); n; n = walker.nextNode()) if (n.length) texts.push(n);+ const node = last ? texts.at(-1) : texts[0];+ const r = document.createRange(); const start = last ? node.length - 1 : 0;+ r.setStart(node, start); r.setEnd(node, start + 1);+ const rect = r.getBoundingClientRect(); return { top: rect.top, left: rect.left, right: rect.right, width: rect.width };+ };+ const a = rectAt(rows[0], true), b = rectAt(rows[1], false);+ const right = rows[0].closest("pre").getBoundingClientRect().right;+ selection.removeAllRanges();+ return { ...result, a, b, right };+ });+ check(selection.text === selection.expected && !selection.text.includes("\n"), "native selection inserted a false code newline");+ if (selection.a.right + selection.a.width < selection.right - 1)+ check(Math.abs(selection.a.top - selection.b.top) < 1, "logical line has a forced visual break at its fragment seam");++ await page.evaluate(() => window.__reasoning.run({ text: Array.from({ length: 3000 }, (_, i) => `word${String(i).padStart(4, "0")}`).join(" "), chunk: 4000, gap: 800 }));+ await page.waitForFunction(() => document.querySelector('[data-slot="reasoning-text"]')?.textContent.length >= 12000);+ await page.mouse.move(550, 350); await page.mouse.wheel(0, -1500);+ await page.waitForTimeout(150);+ const anchor = await page.evaluate(() => {+ const paragraph = document.querySelector('[data-slot="reasoning-text"] p');+ const text = paragraph.firstChild;+ const viewport = document.querySelector(".aui-thread-viewport").getBoundingClientRect();+ for (const match of text.textContent.matchAll(/word\d{4}/g)) {+ const range = document.createRange(); range.setStart(text, match.index); range.setEnd(text, match.index + match[0].length);+ const top = range.getBoundingClientRect().top;+ if (top > viewport.top + 40 && top < viewport.top + 150) return { text: match[0], top };+ }+ throw new Error("no visible word inside tall paragraph");+ });+ await page.waitForSelector('[data-slot="reasoning-transcript"]');+ await page.waitForTimeout(250);+ const after = await page.evaluate((anchor) => {+ const root = document.querySelector('[data-slot="reasoning-text"]');+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const start = node.textContent.indexOf(anchor.text); if (start < 0) continue;+ const range = document.createRange(); range.setStart(node, start); range.setEnd(node, start + anchor.text.length);+ return range.getBoundingClientRect().top;+ }+ return null;+ }, anchor);+ check(after !== null && Math.abs(after - anchor.top) < 30, `tall-block threshold anchor drifted: ${after - anchor.top}px`);+ await page.waitForFunction(() => window.__reasoning.stats().done);++ await page.evaluate(() => window.__reasoning.seed({ text: "Earlier thought.\n\n".repeat(1000) + "```mermaid\ngraph TD\nA-->B\n```" }));+ await page.mouse.move(550, 350); await page.mouse.wheel(0, 100000);+ await page.waitForSelector('[data-streamdown="mermaid-block"]', { timeout: 15000 });+ await page.evaluate(() => window.__reasoning.seed({ text: "| Item | Value |\n| :--- | ---: |\n" + "| bird | 42 |\n".repeat(3000) }));+ await page.mouse.move(550, 350); await page.mouse.wheel(0, 100000);+ await page.waitForTimeout(500);+ check(await page.locator('[data-table-continuation] table').count() > 0, "table continuation became plain text");+ check(await page.locator('[data-table-continuation] thead').first().evaluate((node) => getComputedStyle(node).display) === "none", "table continuation repeated its header");+ for (const language of ["svg", "SVG", "xml", "html"]) {+ await page.evaluate((language) => window.__reasoning.seed({ text: "Earlier thought.\n\n".repeat(1000) + '```' + language + '\n<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80"><circle cx="40" cy="40" r="30"/></svg>\n```' }), language);+ await page.mouse.wheel(0, 100000);+ await page.waitForFunction(() => {+ const image = document.querySelector('img[alt="SVG preview"]');+ return image?.complete && image.naturalWidth > 0;+ });+ check(await page.getByAltText("SVG preview").count() === 1, `bounded ${language} SVG preview did not load`);+ }+ await page.evaluate(() => window.__reasoning.seed({ text: "Earlier thought.\n\n".repeat(1000) + '```html\n<!doctype html><html><head><title>Fence regression</title></head><body>Game</body></html>\n```' }));+ await page.mouse.wheel(0, 100000);+ await page.getByRole("button", { name: "Open HTML preview preview", exact: true }).waitFor();++ const codeSource = "const bird = { x: 80, y: 140, velocity: 0 };\n".repeat(1000).trimEnd();+ await page.evaluate((source) => {+ const open = "```javascript\n" + source + "\n";+ window.__reasoning.run({ text: open + "```\n\n" + "Later thought.\n\n".repeat(6000), chunk: open.length, gap: 4000 });+ }, codeSource);+ await page.waitForTimeout(250);+ await page.mouse.wheel(0, -100000);+ await page.waitForTimeout(400);+ check(await page.getByTitle("Copy code", { exact: true }).isDisabled(), "open large fence allowed copy while streaming");+ check(await page.getByTitle("Download file", { exact: true }).isDisabled(), "open large fence allowed download while streaming");+ await page.waitForFunction(() => document.querySelector('button[title="Copy code"]:not(:disabled)'));+ check(!await page.evaluate(() => window.__reasoning.stats().done), "fence actions only enabled after all reasoning finished");+ await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);+ await page.getByTitle("Copy code", { exact: true }).click();+ check(await page.evaluate(() => navigator.clipboard.readText()) === codeSource, "fence copy lost offscreen code");+ const downloadPromise = page.waitForEvent("download");+ await page.getByTitle("Download file", { exact: true }).click();+ const download = await downloadPromise;+ const chunks = []; for await (const chunk of await download.createReadStream()) chunks.push(chunk.toString());+ check(chunks.join("") === codeSource, "fence download lost offscreen code");+ check(!await page.evaluate(() => window.__reasoning.stats().done), "copy/download test did not run during later streaming prose");+ await page.waitForFunction(() => window.__reasoning.stats().done);+ return { passed: true, streaming, longLineSelectionLength: selection.text.length, tallParagraphDrift: after - anchor.top };+}diff --git a/tests/studio/reasoning-transcript-checks.js b/tests/studio/reasoning-transcript-checks.jsnew file mode 100644index 00000000000..0596d565616--- /dev/null+++ b/tests/studio/reasoning-transcript-checks.js@@ -0,0 +1,153 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Run with playwright-cli run-code --filename=tests/studio/reasoning-transcript-checks.js+// after opening smoke-reasoning-transcript.html in a named browser session.+async (page) => {+ const check = (condition, message) => { if (!condition) throw new Error(message); };+ await page.setViewportSize({ width: 1280, height: 900 });+ await page.waitForFunction(() => window.__reasoning);+ await page.evaluate(() => window.__reasoning.seed({ size: 100000 }));+ await page.waitForTimeout(600);+ check(await page.locator('[data-slot="reasoning-transcript"]').count() === 1, "long reasoning is not windowed");+ check(await page.locator('[data-slot="reasoning-page-navigation"], [data-slot="reasoning-oversized-code"]').count() === 0, "pagination chrome remains");+ check((await page.locator('[data-slot="reasoning-text"]').innerText()).includes("REASONING_END"), "latest reasoning is missing");+ check((await page.evaluate(() => window.__reasoning.stats())).mounted < 20000, "saved trace mounted unbounded content");++ await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);+ await page.getByRole("button", { name: "Copy reasoning", exact: true }).click();+ check(await page.evaluate(async () => await navigator.clipboard.readText() === window.__reasoning.source()), "copy lost source bytes");+ const trigger = page.locator('[data-slot="reasoning-trigger"]');+ await trigger.click();+ await page.waitForTimeout(400);+ check(await page.locator('[data-slot="reasoning-transcript"]').count() === 0, "collapsed reasoning stayed mounted");+ const headerTop = (await trigger.boundingBox()).y;+ await trigger.click();+ await page.waitForTimeout(400);+ check(Math.abs((await trigger.boundingBox()).y - headerTop) < 3, "reopening moved the header");+ check((await page.locator('[data-slot="reasoning-text"]').innerText()).includes("Flappy Bird game"), "reopening did not expose the beginning");+ await page.screenshot({ path: ".playwright-cli/reasoning-inline-desktop.png" });++ await page.evaluate(() => window.__reasoning.run({ size: 24000, chunk: 1024, gap: 120 }));+ await page.waitForFunction(() => (document.querySelector('[data-slot="reasoning-text"]')?.textContent.length ?? 0) > 8000);+ await page.mouse.move(550, 350);+ await page.mouse.wheel(0, -700);+ await page.waitForTimeout(200);+ const thresholdAnchor = await page.locator('[data-slot="reasoning-text"] p').evaluateAll((nodes) => {+ const node = nodes.find((node) => node.getBoundingClientRect().top > 100 && node.getBoundingClientRect().bottom < 600);+ return { text: node.textContent, top: node.getBoundingClientRect().top };+ });+ await page.waitForSelector('[data-slot="reasoning-transcript"]');+ await page.waitForTimeout(300);+ const afterThreshold = page.locator('[data-slot="reasoning-text"] p').filter({ hasText: thresholdAnchor.text }).first();+ check(await afterThreshold.count() === 1, "threshold activation lost the reading passage");+ check(Math.abs((await afterThreshold.boundingBox()).y - thresholdAnchor.top) < 30, "threshold activation moved the reading passage");+ await page.waitForFunction(() => window.__reasoning.stats().done);++ await page.evaluate(() => window.__reasoning.run({ size: 250000, kind: "mixed", chunk: 1024, gap: 30,+ userPrompt: "Create a dynamic demonstration with electrical arcs and interactive objects. ".repeat(30),+ }));+ await page.waitForSelector('[data-slot="reasoning-transcript"]');+ await page.waitForTimeout(400);+ await page.mouse.move(550, 350);+ await page.mouse.wheel(0, -800);+ await page.waitForTimeout(300);+ const anchor = await page.evaluate(() => {+ const viewport = document.querySelector(".aui-thread-viewport").getBoundingClientRect();+ const row = [...document.querySelectorAll("[data-reasoning-fragment]")].find((node) => {+ const rect = node.getBoundingClientRect();+ return rect.top >= viewport.top && rect.bottom < viewport.bottom - 180;+ });+ if (!row) throw new Error("no visible anchor");+ return { key: row.dataset.reasoningFragment, top: row.getBoundingClientRect().top, text: row.textContent };+ });+ await page.waitForTimeout(900);+ const anchored = page.locator(`[data-reasoning-fragment="${anchor.key}"]`);+ check(await anchored.count() === 1, "reading anchor was recycled during streaming");+ check(Math.abs((await anchored.boundingBox()).y - anchor.top) < 3, "streaming moved the reading anchor");+ check(await anchored.textContent() === anchor.text, "streaming changed an earlier thought");+ await page.setViewportSize({ width: 700, height: 900 });+ await page.waitForTimeout(300);+ check(await anchored.count() === 1, "resizing lost the reading passage");+ check(Math.abs((await anchored.boundingBox()).y - anchor.top) < 100, "resizing jumped to another passage");+ await page.setViewportSize({ width: 1280, height: 900 });+ await page.waitForTimeout(300);+ await anchored.evaluate((node) => {+ const range = document.createRange(); range.selectNodeContents(node);+ const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);+ });+ const selected = await page.evaluate(() => window.getSelection().toString());+ await page.mouse.wheel(0, -2000);+ await page.waitForTimeout(500);+ check(await page.evaluate(() => window.getSelection().toString()) === selected, "recycling destroyed selection");+ await page.evaluate(() => window.getSelection().removeAllRanges());+ await trigger.click();+ await page.waitForTimeout(300);+ const liveHeaderTop = (await trigger.boundingBox()).y;+ await trigger.click();+ await page.waitForTimeout(400);+ check(Math.abs((await trigger.boundingBox()).y - liveHeaderTop) < 3, "reopening live reasoning moved its header");+ check((await page.locator('[data-slot="reasoning-text"]').innerText()).includes("Flappy Bird game"), "live reopening reused a stale reading anchor");+ await page.getByRole("button", { name: "Scroll to bottom", exact: true }).click();+ await page.waitForFunction(() => window.__reasoning.stats().done, null, { timeout: 30000 });+ await page.waitForTimeout(500);+ check((await page.locator('[data-slot="reasoning-text"]').innerText()).includes("REASONING_END"), "following did not resume");++ await page.evaluate(() => window.__reasoning.seed({+ size: 100000,+ userPrompt: "Create a dynamic demonstration with electrical arcs and interactive objects. ".repeat(30),+ }));+ await page.waitForTimeout(500);+ await trigger.click();+ await page.waitForTimeout(300);+ const longPromptHeaderTop = (await trigger.boundingBox()).y;+ await trigger.click();+ await page.waitForTimeout(400);+ check(Math.abs((await trigger.boundingBox()).y - longPromptHeaderTop) < 3, "long prompt reopening moved the header");+ await page.mouse.move(550, 350);+ await page.mouse.wheel(0, 100000);+ await page.waitForTimeout(300);+ await page.mouse.move(550, 350);+ await page.mouse.wheel(0, -1500);+ await page.waitForTimeout(400);+ const narrowAnchor = await page.locator('[data-slot="reasoning-text"] p').evaluateAll((nodes) => {+ const node = nodes.find((node) => node.getBoundingClientRect().top > 100 && node.getBoundingClientRect().top < 400);+ if (!node) throw new Error("no resize passage");+ return { text: node.textContent, top: node.getBoundingClientRect().top };+ });+ await page.setViewportSize({ width: 390, height: 844 });+ await page.waitForTimeout(500);+ const narrowPassage = page.locator('[data-slot="reasoning-text"] p').filter({ hasText: narrowAnchor.text }).first();+ check(await narrowPassage.count() === 1, "long prompt reflow recycled the reading passage");+ check(Math.abs((await narrowPassage.boundingBox()).y - narrowAnchor.top) < 100, "long prompt reflow lost the reading position");+ await page.evaluate(() => window.__reasoning.seed({ size: 140000, kind: "code" }));+ await page.waitForTimeout(500);+ check(await page.locator('[data-slot="reasoning-code-fragment"]').count() > 0, "large fence has no code rendering");+ check(await page.locator(".aui-thread-viewport").evaluate((node) => node.scrollWidth <= node.clientWidth + 1), "reasoning overflows the narrow viewport");+ await page.screenshot({ path: ".playwright-cli/reasoning-inline-mobile.png" });+ await page.evaluate(() => document.documentElement.classList.add("dark"));+ await page.emulateMedia({ reducedMotion: "reduce" });+ await page.screenshot({ path: ".playwright-cli/reasoning-inline-mobile-dark.png" });+ await page.evaluate(() => document.documentElement.classList.remove("dark"));+ await page.emulateMedia({ reducedMotion: "no-preference" });+ await page.setViewportSize({ width: 1280, height: 900 });+ await page.evaluate(() => window.__reasoning.seed({ text:+ "Earlier paragraph.\n\n".repeat(1000) + "[Link][ref]\n\n> [ref]: https://example.org",+ }));+ await page.mouse.move(550, 350); await page.mouse.wheel(0, 100000);+ await page.waitForTimeout(500);+ check(await page.getByRole("link", { name: "Link", exact: true }).getAttribute("href") === "https://example.org/", "fragmented reference lost its document definition");+ for (const marker of ["1. ", "- Parent\n 1. ", "> 1. "]) {+ await page.evaluate((marker) => window.__reasoning.seed({ text: marker + "Long item ".repeat(3000) + "\n2. Second item" }), marker);+ await page.mouse.wheel(0, 100000);+ await page.waitForTimeout(500);+ const continuation = page.locator("li[data-reasoning-list-continuation]").last();+ check(await continuation.count() === 1, "long list item lost its continuation container");+ check(await continuation.evaluate((node) => getComputedStyle(node).listStyleType) === "none", "continuation repeated its marker");+ const sibling = page.locator("li").filter({ hasText: /^Second item$/ }).last();+ check(await sibling.count() === 1, "continuation swallowed a genuine sibling item");+ check(await sibling.evaluate((node) => getComputedStyle(node).listStyleType) !== "none", "real sibling lost its marker");+ }+ await page.screenshot({ path: ".playwright-cli/reasoning-review-formatting.png" });+ return { passed: true, checks: ["bounded saved trace", "no pagination chrome", "canonical copy", "collapse/reopen", "live collapse/reopen", "threshold anchor", "streaming anchor", "resize anchor", "long prompt reflow", "selection", "resume following", "narrow code", "light/dark", "document reference links", "list continuation markers"] };+}diff --git a/tests/studio/test_chat_response_details_ui_contract.py b/tests/studio/test_chat_response_details_ui_contract.pyindex ba8dbf7861f..a14f7d4e5a2 100644--- a/tests/studio/test_chat_response_details_ui_contract.py+++ b/tests/studio/test_chat_response_details_ui_contract.py@@ -564,103 +564,21 @@ def test_response_model_badge_is_user_configurable_and_rendered_once_per_message)-def test_reasoning_keeps_streaming_height_cap_through_automatic_collapse():- # Stripped once, here, rather than at each lookup. Every assertion below is about what- # the file DOES, and commented-out code does nothing, so reading the live text is the- # precondition for all of them rather than a precaution for some.+def test_reasoning_uses_continuous_transcript_without_legacy_height_cap():src = _without_block_comments(REASONING_TSX.read_text(encoding = "utf-8"))-- assert "const [retainStreamingHeight, setRetainStreamingHeight]" in src- assert "setRetainStreamingHeight(false)" in src- assert "setRetainStreamingHeight(isReasoningStreaming)" in src- # Still zero while streaming, and still the animation's length once it stops. The two- # collapse mechanisms differ: the height keyframes animate a height captured at toggle- # time, so releasing the cap cannot change what they animate and ANIMATION_DURATION is- # right for them, while `1fr` resolves against the live content every frame and has to- # outlast a transition that only starts a render after this timer is armed.- assert "isReasoningStreaming ? 0 : closeDelay" in src- assert "const closeDelay = GRID_COLLAPSE_REASONING_ENABLED" in src+ assert "retainStreamingHeight" not in src+ assert "resolveReasoningHeightCap" not in src+ assert "<ReasoningTranscript" in src+ assert "useCollapseScrollLock(" in srcassert "? ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MS" in src- assert ": ANIMATION_DURATION;" in src- # The cap is `streaming || retained`, and #11373 moved the render down a level: the state- # lives here and is handed to the child as a prop, which then ORs it with its own- # streaming flag. Which component evaluates it is layout; that it is still ORed, and that- # the retained flag actually reaches the evaluation, is the claim.- # On the element that receives it, not anywhere in the file. The same text in a comment,- # or on some other element, reads identically to a file-wide search and hands nothing- # over; ReasoningText would then OR in its own default-false prop and the cap is lost.- # ReasoningBody is rendered more than once, and the one that matters is the one holding- # this state: it passes isStreaming={isReasoningStreaming}, the flag whose end is what- # the retained height is bridging. Every such call has to hand the retained flag over.- holders = [- tag- for tag in _opening_tags(src, "<ReasoningBody")- # On an attribute boundary, like the retained flag below. Both props are optional, so- # `data-isStreaming={isReasoningStreaming}` satisfies a substring test while- # ReasoningBody receives no isStreaming at all: the tag is still selected as a holder,- # every assertion below still passes, and the live stream is no longer capped.- if re.search(r"(?:^|[\s{])isStreaming=\{isReasoningStreaming\}", tag)- ]- assert holders, (- "no ReasoningBody receives isReasoningStreaming any more, so this guard cannot tell "- "which render is the one whose collapse the retained height exists to smooth"- )- # A spread can supply the same prop and, written after it, wins. Nothing here can say- # what is in one, so a holder that spreads is refused rather than read.- # BOTH props, not the retained flag alone. What is being kept is the OR of the two, so a- # spread that replaces `isStreaming` loses just as much: written between the two- # attributes, `{...{ isStreaming: false }}` leaves the retained flag untouched and this- # check green while ReasoningText stops seeing the live stream and renders uncapped until- # the retained state catches up. `isStreaming` is also what picks the holders above, so a- # spread overriding it makes the selection itself wrong.- spreading = [- tag- for tag in holders- if any(_spread_overrides(tag, prop) for prop in ("isStreaming", "retainStreamingHeight"))- ]- assert not spreading, (- f"a ReasoningBody holding this state spreads props, so whether the streaming flags it "- f"is handed survive depends on what the spread contains, which this guard cannot "- f"resolve: {spreading!r}"- )- # On an attribute boundary. Both props are optional, so `data-retainStreamingHeight=`- # satisfies a substring search while the component falls back on its default of false.- missing = [- tag- for tag in holders- if not re.search(r"(?:^|[\s{])retainStreamingHeight=\{retainStreamingHeight\}", tag)- ]- assert not missing, (- f"the retained-height flag no longer reaches the component that renders the block, "- f"so nothing can OR it into the streaming cap: {missing!r}"- )- # On ReasoningText specifically. It is the element that writes data-streaming and so owns- # the height cap; the same OR on a sibling reads identically here and caps nothing.- tag = _opening_tag(src, "<ReasoningText")- assert tag, "ReasoningText is no longer rendered, so nothing here caps the height"- # Same ground as the holder above, and it has to be said again here: JSX takes the last- # write of a prop, so a spread after `streaming=` decides the cap and the explicit text- # this guard reads goes on satisfying it.- assert not _spread_overrides(tag, "streaming"), (- f"ReasoningText spreads props after its streaming prop, so whether the cap it is "- f"given survives "- f"depends on what the spread contains, which this guard cannot resolve: {tag!r}"- )- # The left operand has to be the component's own streaming input. `\w+` accepted any- # identifier, so `streaming={somethingElse || retainStreamingHeight}` passed while an- # actively streaming block went uncapped whenever the retained flag was false.- assert re.search(r"(?:^|[\s{])streaming=\{isStreaming \|\| retainStreamingHeight\}", tag), (- f"ReasoningText's streaming prop no longer ORs in retainStreamingHeight, so the block "- f"collapses to its idle height the moment streaming stops, which is the jump this "- f"test exists for: {tag!r}"- )+ assert ": ANIMATION_DURATION," in srcdef test_reasoning_clears_manual_open_on_a_new_stream():"""A hand-opened block must not stay pinned open when the stream restarts.- isOpen is `(streaming && !dismissed) || manualOpen` and manualOpen is only- settable while idle, so the new-stream reset has to clear it too.+ A nullable manual override outranks the visibility preference for one round;+ the next stream must return control to that preference."""src = _without_block_comments(REASONING_TSX.read_text(encoding = "utf-8"))@@ -701,28 +619,13 @@ def test_reasoning_clears_manual_open_on_a_new_stream():# It is the hand toggle that writes it. Without this the override could be some derived# value the reader never sets, and clearing it would say nothing about a pinned block.- toggle_at = src.find("resolveReasoningToggle(")- assert toggle_at != -1, "reasoning.tsx no longer resolves its open toggle, so nothing here "- handler = src[src.rfind("useCallback(", 0, toggle_at) : src.find("\n );", toggle_at)]- # With the value the toggle RESOLVED, not merely called with something. `setOverride(null)`- # in the handler satisfies "the setter is invoked" while no hand toggle is ever remembered,- # which makes the new-round reset below guard nothing at all.- resolved = re.search(rf"{re.escape(writes)}\(\s*([A-Za-z_$][\w$.]*)\s*\)", handler)- assert resolved and resolved.group(1) != "null", (- f"the open toggle does not store the override it resolved: it writes "- f"{resolved.group(1) if resolved else 'something this guard cannot read'!r}. A hand "- f"toggle is then never remembered, and clearing the override on a new round guards "- f"nothing"+ handler = re.search(+ r"const handleOpenChange = useCallback\(\s*\(open: boolean\) => \{(.*?)\n \}",+ src[src.index("const [override,") :],+ re.S,)- # Its `override`, by name. Requiring only the `next.` prefix let- # `setOverride(next.releaseStreamingHeight)` pass: both fields are booleans so it- # type-checks, but reopening a hand-closed block whose setting defaults open wants- # override true while releaseStreamingHeight is false, and the block stays shut.- answer = re.search(r"const (\w+) = resolveReasoningToggle\(", handler)- assert answer and resolved.group(1) == f"{answer.group(1)}.override", (- f"the open toggle writes {resolved.group(1)!r}, which is not the answer "- f"resolveReasoningToggle returned, so what the reader asked for and what is stored "- f"can differ"+ assert handler and f"{writes}(open);" in handler.group(1), (+ "the hand toggle must store the requested open state directly")# And a new round clears it. Regenerate reuses this component instance, so without this a