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: keep long reasoning responsive with bounded pages (#10717)
Wasim Yousef Said27a4ff6a9b47
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex c35a8ae364b..84bc96d6042 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -813,50 +813,35 @@ function useCoalescedStreamingText(/** False inside the reasoning block, which renders through this same component. */export const SearchImagesEnabledContext = createContext(true);-const MarkdownTextImpl = () => {- const allowSearchImages = useContext(SearchImagesEnabledContext);- const aui = useAui();- const { text, status } = useMessagePartText();- const partIndex =- aui.part.source === "message" && aui.part.query.type === "index"- ? aui.part.query.index- : 0;- // Parts are keyed by index, so switching conversations hands this instance a different message, and Streamdown- // only extends its parsed blocks: key it per message. The cache generation joins the key for the case the- // Markdown string cannot express, an edit that drops retained blocks without changing the tail.- const messageId = useAuiState(({ message }) => message.id);- // Read once here for every block below: see RenderHtmlToolPresenceContext.- const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>- message.parts.some(isRenderableRenderHtmlToolPart),- );- // A string, not the Map: selector results are compared by identity.- const searchImagesKey = useAuiState(({ message }) =>- allowSearchImages ? searchImagesSignature(message.parts) : "",- );+type MarkdownTextRendererProps = {+ isStreaming: boolean;+ messageHasRenderableRenderHtmlTool: boolean;+ messageId: string;+ messageTextKey: string;+ precedingText: string;+ searchImagesKey: string;+ statusType: string;+ text: string;+};++function MarkdownTextRenderer({+ isStreaming,+ messageHasRenderableRenderHtmlTool,+ messageId,+ messageTextKey,+ precedingText,+ searchImagesKey,+ statusType,+ text,+}: MarkdownTextRendererProps) {const searchImages = useMemo(() => parseSearchImagesSignature(searchImagesKey),[searchImagesKey],);- // What earlier text parts said, so a subject named in two of them gets one card.- const precedingText = useAuiState(({ message }) =>- allowSearchImages- ? precedingTextForMessagePart(message.parts, partIndex)- : "",- );- const messageTextKey = useAuiState(({ message }) =>- allowSearchImages- ? JSON.stringify(- message.parts- .filter((part) => part.type === "text")- .map((part) => part.text),- )- : "[]",- );const messageTexts = useMemo(() => JSON.parse(messageTextKey) as string[],[messageTextKey],);- const isStreaming = status.type === "running";const displayText = useCoalescedStreamingText(text, isStreaming, messageId);const processedText = useMemo(() =>@@ -909,7 +894,7 @@ const MarkdownTextImpl = () => {value={messageHasRenderableRenderHtmlTool}><SearchImagesContext.Provider value={searchImages}>- <div data-status={status.type} className="min-w-0 max-w-full">+ <div data-status={statusType} className="min-w-0 max-w-full"><Streamdownkey={`${messageId}:${incrementalCache.renderGeneration}:${renderKey}`}mode="streaming"@@ -935,6 +920,86 @@ const MarkdownTextImpl = () => {</SearchImagesContext.Provider></RenderHtmlToolPresenceContext.Provider>);+}++const MarkdownTextImpl = () => {+ const allowSearchImages = useContext(SearchImagesEnabledContext);+ const aui = useAui();+ const { text, status } = useMessagePartText();+ const partIndex =+ aui.part.source === "message" && aui.part.query.type === "index"+ ? aui.part.query.index+ : 0;+ // Parts are keyed by index, so switching conversations hands this instance a+ // different message, and Streamdown only extends its parsed blocks: key it per+ // message. The cache generation joins the key for the case the Markdown string+ // cannot express, an edit that drops retained blocks without changing the tail.+ const messageId = useAuiState(({ message }) => message.id);+ // Read once here for every block below: see RenderHtmlToolPresenceContext.+ const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>+ message.parts.some(isRenderableRenderHtmlToolPart),+ );+ // A string, not the Map: selector results are compared by identity.+ const searchImagesKey = useAuiState(({ message }) =>+ allowSearchImages ? searchImagesSignature(message.parts) : "",+ );+ // What earlier text parts said, so a subject named in two of them gets one card.+ const precedingText = useAuiState(({ message }) =>+ allowSearchImages+ ? precedingTextForMessagePart(message.parts, partIndex)+ : "",+ );+ const messageTextKey = useAuiState(({ message }) =>+ allowSearchImages+ ? JSON.stringify(+ message.parts+ .filter((part) => part.type === "text")+ .map((part) => part.text),+ )+ : "[]",+ );++ return (+ <MarkdownTextRenderer+ isStreaming={status.type === "running"}+ messageHasRenderableRenderHtmlTool={messageHasRenderableRenderHtmlTool}+ messageId={messageId}+ messageTextKey={messageTextKey}+ precedingText={precedingText}+ searchImagesKey={searchImagesKey}+ statusType={status.type}+ text={text}+ />+ );+};++type MarkdownTextSourceProps = {+ messageHasRenderableRenderHtmlTool: boolean;+ messageId: string;+ sourceText: string;+ streaming: boolean;};+const MarkdownTextSourceImpl = ({+ messageHasRenderableRenderHtmlTool,+ messageId,+ sourceText,+ streaming,+}: MarkdownTextSourceProps) => (+ <MarkdownTextRenderer+ isStreaming={streaming}+ messageHasRenderableRenderHtmlTool={messageHasRenderableRenderHtmlTool}+ messageId={messageId}+ messageTextKey="[]"+ precedingText=""+ searchImagesKey=""+ statusType={streaming ? "running" : "complete"}+ text={sourceText}+ />+);+export const MarkdownText = withSmoothContextProvider(MarkdownTextImpl);+// Reasoning pages 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;\ No newline at end of filediff --git a/studio/frontend/src/components/assistant-ui/reasoning-pagination.ts b/studio/frontend/src/components/assistant-ui/reasoning-pagination.tsnew file mode 100644index 00000000000..dbe0eeafed3--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/reasoning-pagination.ts@@ -0,0 +1,358 @@+// 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;+ if (!isInsideFence(candidate, fences)) {+ return candidate;+ }+ cursor = candidate;+ }+ }++ return avoidBrokenSurrogate(markdown, target);+}++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.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsxindex 95b21a07b04..684e2fe0202 100644--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx@@ -7,8 +7,16 @@import {MarkdownText,+ MarkdownTextSource,SearchImagesEnabledContext,} from "@/components/assistant-ui/markdown-text";+import {+ type ReasoningPageBoundary,+ ReasoningPageSelector,+ createReasoningPageBoundary,+ isReasoningPageBoundaryValid,+ shouldPaginateReasoning,+} from "@/components/assistant-ui/reasoning-pagination";import {Collapsible,CollapsibleContent,@@ -28,6 +36,7 @@ import {startsNewReasoningRound,useChatPreferencesStore,} from "@/features/chat";+import { isRenderableRenderHtmlToolPart } from "@/features/chat/artifacts/html-fences";import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";import { cn } from "@/lib/utils";import {@@ -47,12 +56,29 @@ import {memo,useCallback,useEffect,+ useMemo,useRef,useState,} from "react";+import { useShallow } from "zustand/react/shallow";const ANIMATION_DURATION = 200;const AUTO_SCROLL_THRESHOLD_PX = 24;+function selectionIntersectsElement(+ selection: Selection | null,+ element: Element | null,+): boolean {+ if (!selection || selection.isCollapsed || !element) {+ return false;+ }+ for (let index = 0; index < selection.rangeCount; index += 1) {+ if (selection.getRangeAt(index).intersectsNode(element)) {+ return true;+ }+ }+ return false;+}+export const reasoningVariants = cva("aui-reasoning-root mt-3 mb-4 w-full", {variants: {variant: {@@ -241,21 +267,28 @@ function ReasoningContent({}function ReasoningText({+ autoScroll,className,+ pageKey,streaming,children,...props-}: ComponentProps<"div"> & { streaming?: boolean }) {+}: 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 && scrollRef.current)) {+ 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) {@@ -297,8 +330,13 @@ function ReasoningText({el.removeEventListener("scroll", updateAutoScroll);el.removeEventListener("wheel", handleWheel);};- }, [streaming]);+ }, [autoScroll, streaming]);+ useEffect(() => {+ if (autoScroll === false && scrollRef.current) {+ scrollRef.current.scrollTop = 0;+ }+ }, [autoScroll, pageKey]);return (<divref={scrollRef}@@ -332,7 +370,81 @@ const ReasoningImpl: ReasoningMessagePartComponent = () => (const COPY_RESET_MS = 2000;-function ReasoningCopyButton({ startIndex, endIndex }: { startIndex: number; endIndex: number }) {+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>+ <pre className="max-w-full overflow-x-auto whitespace-pre-wrap break-words rounded-md bg-muted/40 p-3 font-mono text-xs">+ {source}+ </pre>+ </div>+ );+}+function ReasoningCopyButton({+ startIndex,+ endIndex,+}: { startIndex: number; endIndex: number }) {const [copied, setCopied] = useState(false);const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -402,6 +514,145 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({return true;});+ const messageId = useAuiState(({ message }) => message.id);++ const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>+ message.parts.some(isRenderableRenderHtmlToolPart),+ );++ const reasoningContentRef = useRef<HTMLDivElement>(null);++ const reasoningDocuments = useAuiState(+ useShallow(({ message }) =>+ message.parts+ .slice(startIndex, endIndex + 1)+ .filter((part) => part.type === "reasoning")+ .map((part) => ("text" in part ? (part as { text: string }).text : "")),+ ),+ );+ 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.+ 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 (+ !selectionIntersectsElement(+ window.getSelection(),+ reasoningContentRef.current,+ )+ ) {+ startPagination();+ return;+ }+ const handleSelectionChange = () => {+ if (+ !selectionIntersectsElement(+ window.getSelection(),+ reasoningContentRef.current,+ )+ ) {+ startPagination();+ }+ };+ 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 && isReasoningStreaming && selectedEnd === null,+ }),+ [+ isReasoningStreaming,+ 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]);+const persistedDuration = useAuiState(({ message }) => {return resolveReasoningGroupDuration(message.parts,@@ -513,11 +764,46 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({<ReasoningContentaria-busy={isReasoningStreaming}streaming={isReasoningStreaming}+ ref={reasoningContentRef}>+ {paginationActive && (+ <ReasoningPageNavigation+ hasEarlier={page.hasEarlier}+ hasNewer={page.hasNewer}+ onEarlier={showEarlierPage}+ onNewer={showNewerPage}+ onLatest={showLatestPage}+ start={page.start}+ end={page.end}+ total={reasoningText.length}+ />+ )}<ReasoningText+ autoScroll={viewingLatestPage}+ pageKey={paginationActive ? `${page.start}:${page.end}` : undefined}streaming={isReasoningStreaming || retainStreamingHeight}>- {children}+ {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={isReasoningStreaming && viewingLatestPage}+ />+ </SearchImagesEnabledContext.Provider>+ )}+ </>+ ) : (+ children+ )}</ReasoningText></ReasoningContent></ReasoningRoot>diff --git a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts b/studio/frontend/tests/composer-keystroke-subscription-budget.test.tsindex 3101c927917..c86a71bdcc2 100644--- a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts+++ b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts@@ -57,13 +57,18 @@ test("a markdown block reads the render_html presence from context, not the stortest("the render_html scan happens once per message part, above the blocks", () => {const impl = body(markdown, "const MarkdownTextImpl = () => {", "\n};");+ const renderer = body(+ markdown,+ "function MarkdownTextRenderer({",+ "\nconst MarkdownTextImpl",+ );assert.match(impl,/useAuiState\(\(\{ message \}\) =>\s*message\.parts\.some\(isRenderableRenderHtmlToolPart\),?\s*\)/,);// The value has to reach the blocks, or the context read above answers with its default.assert.match(- impl,+ renderer,/<RenderHtmlToolPresenceContext\.Provider\s+value=\{messageHasRenderableRenderHtmlTool\}/,);});diff --git a/studio/frontend/tests/reasoning-document-pagination.test.ts b/studio/frontend/tests/reasoning-document-pagination.test.tsnew file mode 100644index 00000000000..e8005a0be99--- /dev/null+++ b/studio/frontend/tests/reasoning-document-pagination.test.ts@@ -0,0 +1,98 @@+// 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-pagination.test.ts b/studio/frontend/tests/reasoning-pagination.test.tsnew file mode 100644index 00000000000..6d15fe7867c--- /dev/null+++ b/studio/frontend/tests/reasoning-pagination.test.ts@@ -0,0 +1,182 @@+// 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);+});diff --git a/studio/frontend/tests/reasoning-selection-pagination.test.ts b/studio/frontend/tests/reasoning-selection-pagination.test.tsnew file mode 100644index 00000000000..96ef4c6bd0b--- /dev/null+++ b/studio/frontend/tests/reasoning-selection-pagination.test.ts@@ -0,0 +1,20 @@+// 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 { readText } from "./helpers/kit.ts";++const REASONING = readText("../src/components/assistant-ui/reasoning.tsx");+const INTERSECTION_HELPER =+ /function selectionIntersectsElement\([\s\S]*?selection\.getRangeAt\(index\)\.intersectsNode\(element\)/;+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", () => {+ 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/reasoning-source-render.test.ts b/studio/frontend/tests/reasoning-source-render.test.tsnew file mode 100644index 00000000000..860ee478fb7--- /dev/null+++ b/studio/frontend/tests/reasoning-source-render.test.ts@@ -0,0 +1,143 @@+// 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 { execFile } from "node:child_process";+import test from "node:test";+import { promisify } from "node:util";++const execFileAsync = promisify(execFile);++// Vite's Markdown plugin graph retains close hooks after SSR. Run the real+// renderer in an isolated process so the assertion owns its complete lifetime+// and can terminate those hooks after the markup has been produced.+const RENDER_SOURCE_WITHOUT_PART_SCOPE = String.raw`+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import {+ AssistantRuntimeProvider,+ useLocalRuntime,+} from "@assistant-ui/react";+import { createServer } from "vite";++const vite = await createServer({+ appType: "custom",+ logLevel: "silent",+ optimizeDeps: { noDiscovery: true },+ server: { middlewareMode: true, watch: null },+});+const loaded = await vite.ssrLoadModule(+ "/src/components/assistant-ui/markdown-text.tsx",+);+const MarkdownTextSource = loaded.MarkdownTextSource;+const adapter = {+ async *run() {+ yield { content: [{ type: "text", text: "unused" }] };+ },+};+function GroupScopeHarness() {+ const runtime = useLocalRuntime(adapter);+ return createElement(+ AssistantRuntimeProvider,+ { runtime },+ createElement(MarkdownTextSource, {+ messageId: "reasoning-group-message",+ sourceText: "Group-scoped **reasoning page**",+ streaming: false,+ }),+ );+}+const html = renderToStaticMarkup(createElement(GroupScopeHarness));+process.stdout.write(html, () => process.exit(0));+`;++const RENDER_SOURCE_WITH_RENDER_HTML_SIBLING = String.raw`+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import {+ AssistantRuntimeProvider,+ useLocalRuntime,+} from "@assistant-ui/react";+import { createServer } from "vite";++const virtualId = "virtual:reasoning-source-render";+const resolvedId = "\0" + virtualId;+const vite = await createServer({+ appType: "custom",+ logLevel: "silent",+ optimizeDeps: { noDiscovery: true },+ server: { middlewareMode: true, watch: null },+ plugins: [{+ name: "reasoning-source-render",+ resolveId(id) {+ return id === virtualId ? resolvedId : undefined;+ },+ load(id) {+ if (id !== resolvedId) return undefined;+ return 'export { MarkdownTextSource } from "/src/components/assistant-ui/markdown-text.tsx"; export { useChatRuntimeStore } from "/src/features/chat/index.ts";';+ },+ }],+});+const loaded = await vite.ssrLoadModule(virtualId);+Object.assign(loaded.useChatRuntimeStore.getInitialState(), {+ artifactsEnabled: true,+ collapseHtmlArtifacts: true,+ loadedIsDiffusion: false,+});+const adapter = { async *run() {} };+const sourceText = [+ "\`\`\`html",+ "<!DOCTYPE html>",+ "<html><body>reasoning HTML fence</body></html>",+ "\`\`\`",+].join(String.fromCharCode(10));+function GroupScopeHarness() {+ const runtime = useLocalRuntime(adapter);+ return createElement(+ AssistantRuntimeProvider,+ { runtime },+ createElement(loaded.MarkdownTextSource, {+ messageHasRenderableRenderHtmlTool: true,+ messageId: "reasoning-group-message",+ sourceText,+ streaming: false,+ }),+ );+}+const html = renderToStaticMarkup(createElement(GroupScopeHarness));+process.stdout.write(html, () => process.exit(0));+`;++test("source Markdown renders in an assistant root scope without a message part", async () => {+ const { stdout } = await execFileAsync(+ process.execPath,+ ["--input-type=module", "--eval", RENDER_SOURCE_WITHOUT_PART_SCOPE],+ {+ cwd: process.cwd(),+ maxBuffer: 1_000_000,+ timeout: 30_000,+ },+ );++ assert.match(stdout, /Group-scoped/);+ assert.match(+ stdout,+ /<span[^>]+data-streamdown="strong"[^>]*>reasoning page<\/span>/,+ );+});++test("source Markdown suppresses a duplicate HTML card when render_html is present", async () => {+ const { stdout } = await execFileAsync(+ process.execPath,+ ["--input-type=module", "--eval", RENDER_SOURCE_WITH_RENDER_HTML_SIBLING],+ {+ cwd: process.cwd(),+ maxBuffer: 1_000_000,+ timeout: 30_000,+ },+ );++ assert.match(stdout, /data-streamdown="code-block"/);+ assert.match(stdout, /reasoning HTML fence/);+ assert.doesNotMatch(stdout, /Open HTML preview preview/);+});diff --git a/tests/studio/playwright_thread_scoped_settings.py b/tests/studio/playwright_thread_scoped_settings.pyindex 0c5c391dd92..2c12190988d 100644--- a/tests/studio/playwright_thread_scoped_settings.py+++ b/tests/studio/playwright_thread_scoped_settings.py@@ -16,6 +16,7 @@ lets this run in seconds rather than behind a GGUF download.import jsonimport os+import reimport sysimport timeimport uuid@@ -302,6 +303,64 @@ def read_globals(page):)+def check_reasoning_page_navigation(page, token):+ step("saved reasoning pages render the selected source range")+ 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")+ messages = api(page, f"/api/chat/threads/{thread_id}/messages", token = token)["messages"]+ messages.append(+ {+ "id": str(uuid.uuid4()),+ "threadId": thread_id,+ "parentId": messages[0]["id"],+ "role": "assistant",+ "content": [+ {"type": "reasoning", "text": source},+ {"type": "text", "text": "The final answer stays separate."},+ ],+ "createdAt": int(time.time() * 1000),+ }+ )+ api(+ page,+ f"/api/chat/threads/{thread_id}/messages",+ method = "PUT",+ token = token,+ body = {"messages": messages},+ )+ open_thread(page, thread_id)+ page.get_by_role("button", name = "Thought for 0 seconds", exact = True).click()+ navigation = page.get_by_role("navigation", name = "Reasoning pages")+ 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+ expect(page.get_by_text("The final answer stays separate.", exact = True)).to_be_visible()++def main():with sync_playwright() as playwright:browser = playwright.chromium.launch(args = ["--no-sandbox", "--disable-dev-shm-usage"])@@ -458,6 +517,8 @@ 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)+if page_errors:fail(f"page errors during the run: {page_errors[:3]!r}")