Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop a streaming research run re-rendering the whole chat (#8634)
Daniel Hanb9795291ac90
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 126dafbfdbe..076ae6fd71e 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -240,6 +240,7 @@ import {type ReactNode,Fragment,createContext,+ memo,useCallback,useContext,useEffect,@@ -1327,11 +1328,13 @@ const FOOTER_GAP_BELOW_SPACER_PX = 10;// Covers instant responses where isRunning is already false by resize time.const RUN_SHRINK_WINDOW_MS = 1000;+// Memoized: chat-page renders this inline in a store-subscribing component, so a parent render+// would otherwise reconcile the whole message list.export const Thread: FC<{hideComposer?: boolean;hideWelcome?: boolean;targetThreadId?: string;-}> = ({ hideComposer, hideWelcome, targetThreadId }) => {+}> = memo(({ hideComposer, hideWelcome, targetThreadId }) => {// Intent-aware autoscroll replaces assistant-ui's built-in autoscroll to// prevent the streaming-mutation race that snaps the viewport back to the// bottom while the user scrolls up (see the hook for the full explanation).@@ -1642,7 +1645,8 @@ export const Thread: FC<{</PageDragContext.Provider></GeneratedImageOverlayProvider>);-};+});+Thread.displayName = "Thread";const GeneratedImageViewportOverlay: FC<{hideComposer?: boolean;@@ -2041,16 +2045,17 @@ const Composer: FC<{const researchThreadClaimed = useResearchRunStore((state) =>researchThreadId ? Boolean(state.claimedThreadIds[researchThreadId]) : false,);- const activeResearchRun = useResearchRunStore((state) => {+ // Derive in the selector, as useThreadResearchActive does: a bare run selector re-renders the+ // composer on every streamed research delta.+ const isResearchActive = useResearchRunStore((state) => {const runId = researchThreadId? state.latestRunByThreadId[researchThreadId]: undefined;- return runId ? state.sessions[runId]?.run : undefined;+ const run = runId ? state.sessions[runId]?.run : undefined;+ return Boolean(+ run && !["completed", "failed", "cancelled"].includes(run.status),+ );});- const isResearchActive = Boolean(- activeResearchRun &&- !["completed", "failed", "cancelled"].includes(activeResearchRun.status),- );const hasResearchMessage = useAuiState(({ thread }) =>thread.messages.some((message) => {const custom = (@@ -5094,47 +5099,52 @@ const ComposerRightControls: FC<{);const isQueueRunning = Boolean(queueEntry);const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);- const activeResearchRun = useResearchRunStore((state) => {+ // Id and status, not the run: run identity changes on every streamed research delta.+ const activeResearchRunId = useResearchRunStore((state) =>+ activeThreadId ? state.latestRunByThreadId[activeThreadId] : undefined,+ );+ const activeResearchRunStatus = useResearchRunStore((state) => {const runId = activeThreadId? state.latestRunByThreadId[activeThreadId]: undefined;- return runId ? state.sessions[runId]?.run : undefined;+ return runId ? state.sessions[runId]?.run.status : undefined;});const isResearchActive = Boolean(- activeResearchRun &&- !["completed", "failed", "cancelled"].includes(activeResearchRun.status),+ activeResearchRunStatus &&+ !["completed", "failed", "cancelled"].includes(activeResearchRunStatus),);const [stoppingResearchRunId, setStoppingResearchRunId] = useState<string | null>(null);const stoppingResearchRunIdRef = useRef<string | null>(null);const researchStopping = Boolean(- activeResearchRun &&- (activeResearchRun.status === "cancelling" ||- stoppingResearchRunId === activeResearchRun.id),+ activeResearchRunStatus &&+ (activeResearchRunStatus === "cancelling" ||+ (activeResearchRunId !== undefined &&+ stoppingResearchRunId === activeResearchRunId)),);useEffect(() => {if (!isResearchActive ||(stoppingResearchRunIdRef.current &&- stoppingResearchRunIdRef.current !== activeResearchRun?.id)+ stoppingResearchRunIdRef.current !== activeResearchRunId)) {stoppingResearchRunIdRef.current = null;setStoppingResearchRunId(null);}- }, [activeResearchRun?.id, isResearchActive]);+ }, [activeResearchRunId, isResearchActive]);const stop = () => {- if (isResearchActive && activeResearchRun) {+ if (isResearchActive && activeResearchRunId) {if (- activeResearchRun.status === "cancelling" ||- stoppingResearchRunIdRef.current === activeResearchRun.id+ activeResearchRunStatus === "cancelling" ||+ stoppingResearchRunIdRef.current === activeResearchRunId) {return;}if (isQueueRunning) onStopClick?.();- stoppingResearchRunIdRef.current = activeResearchRun.id;- setStoppingResearchRunId(activeResearchRun.id);- void cancelResearchRun(activeResearchRun.id)+ stoppingResearchRunIdRef.current = activeResearchRunId;+ setStoppingResearchRunId(activeResearchRunId);+ void cancelResearchRun(activeResearchRunId).then((run) => ingestResearchUpdate(run)).catch((error) => {stoppingResearchRunIdRef.current = null;diff --git a/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx b/studio/frontend/src/components/assistant-ui/tool-code-cell.tsxindex 6609b8e71b4..b5d7e613f31 100644--- a/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx@@ -4,6 +4,7 @@"use client";import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";import { downloadFile, isDownloadCancelled } from "@/lib/native-files";import { toast } from "@/lib/toast";import { code as codePlugin } from "@streamdown/code";@@ -18,8 +19,6 @@ const SHIKI_THEME = ["github-light", "github-dark"] as ["github-light","github-dark",];-/** Past this the block stays plain monospace: shiki is not worth the main-thread time. */-const MAX_HIGHLIGHT_CHARS = 20_000;/** Within this many px of the bottom counts as following the stream. */const PIN_SLACK_PX = 40;diff --git a/studio/frontend/src/components/markdown/markdown-preview.tsx b/studio/frontend/src/components/markdown/markdown-preview.tsxindex 6421bc0129b..9359d197384 100644--- a/studio/frontend/src/components/markdown/markdown-preview.tsx+++ b/studio/frontend/src/components/markdown/markdown-preview.tsx@@ -1,17 +1,28 @@// 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 { markdownPluginNeeds } from "@/lib/markdown-plugins";import { openLink } from "@/lib/open-link";import { safeMarkdownUrl } from "@/lib/safe-markdown-url";+import { scheduleIdleTask } from "@/lib/schedule-idle-task";import { cn } from "@/lib/utils";import { code } from "@streamdown/code";import { math } from "@streamdown/math";import { mermaid } from "@streamdown/mermaid";-import { type ComponentProps, type ReactElement, memo } from "react";+import {+ type ComponentProps,+ type ReactElement,+ memo,+ useEffect,+ useMemo,+ useState,+} from "react";import { Streamdown } from "streamdown";import "katex/dist/katex.min.css";-const MARKDOWN_PLUGINS = { code, math, mermaid } as const;+type MarkdownPlugins = NonNullable<+ ComponentProps<typeof Streamdown>["plugins"]+>;const MARKDOWN_COMPONENTS = {a: ({ href, children, ...props }: ComponentProps<"a">) => (<a@@ -34,13 +45,41 @@ type MarkdownPreviewProps = {markdown: string;className?: string;plain?: boolean;+ /**+ * Parse on the next idle callback so the surrounding UI paints first. For a document that+ * arrives whole and is big enough to stall - a finished research report - the wait is the same+ * either way, but the window stays interactive through it.+ */+ defer?: boolean;};function MarkdownPreviewImpl({markdown,className,plain = false,+ defer = false,}: MarkdownPreviewProps): ReactElement {+ // Math and mermaid over a document with neither still cost a pass per node, and shiki over a+ // very long one costs more than it is worth; the report lands in one synchronous commit.+ const plugins = useMemo<MarkdownPlugins>(() => {+ const needs = markdownPluginNeeds(markdown);+ const next: MarkdownPlugins = {};+ if (needs.code) next.code = code;+ if (needs.math) next.math = math;+ if (needs.mermaid) next.mermaid = mermaid;+ return next;+ }, [markdown]);+ // Readiness belongs to the markdown value, not the component: resetting it from an effect is+ // one commit late, so the new document is parsed synchronously and thrown away - the stall+ // `defer` exists to avoid, paid twice. Deriving it during render keeps it out of Streamdown.+ const [readyMarkdown, setReadyMarkdown] = useState<string | null>(null);+ const ready = !defer || readyMarkdown === markdown;+ useEffect(() => {+ if (!defer) {+ return;+ }+ return scheduleIdleTask(() => setReadyMarkdown(markdown), 200);+ }, [defer, markdown]);const markdownClassName ="w-full max-w-none min-w-0 space-y-2 [overflow-wrap:anywhere] [&_*]:max-w-none [&_p]:w-full [&_ul]:w-full [&_ol]:w-full [&_li]:w-full [&_h1]:w-full [&_h2]:w-full [&_h3]:w-full [&_h4]:w-full [&_h5]:w-full [&_h6]:w-full [&_pre]:w-full [&_table]:w-full [&_p]:break-words [&_li]:break-words [&_code]:break-words [&_pre]:whitespace-pre-wrap [&_pre]:break-words";@@ -53,16 +92,20 @@ function MarkdownPreviewImpl({className,)}>- <Streamdown- mode="static"- plugins={MARKDOWN_PLUGINS}- components={MARKDOWN_COMPONENTS}- urlTransform={safeMarkdownUrl}- controls={false}- className={markdownClassName}- >- {markdown.trim() ? markdown : "_Empty note_"}- </Streamdown>+ {ready ? (+ <Streamdown+ mode="static"+ plugins={plugins}+ components={MARKDOWN_COMPONENTS}+ urlTransform={safeMarkdownUrl}+ controls={false}+ className={markdownClassName}+ >+ {markdown.trim() ? markdown : "_Empty note_"}+ </Streamdown>+ ) : (+ <div className={markdownClassName} aria-busy="true" />+ )}</div>);}diff --git a/studio/frontend/src/features/chat/api/research-api.ts b/studio/frontend/src/features/chat/api/research-api.tsindex 8e72e2bfe7b..1b4b8938c5d 100644--- a/studio/frontend/src/features/chat/api/research-api.ts+++ b/studio/frontend/src/features/chat/api/research-api.ts@@ -285,11 +285,13 @@ export async function* followResearchRun(try {for await (const event of streamResearchEvents(id, cursor, signal)) {cursor = Math.max(cursor, event.id);- const eventRun: ResearchRun = event.run ?? {- ...currentRun,- lastEventSeq: Math.max(currentRun.lastEventSeq, event.id),- updatedAt: Math.max(currentRun.updatedAt, event.createdAt),- };+ // Delta-only events carry no run by design (`_DELTA_ONLY_EVENTS` in+ // routes/research_runs.py), so reuse the run we hold: report/reasoning deltas arrive+ // ~12x/s for the whole synthesis, and a fresh object per event re-renders every+ // subscriber that selects the run. The cursor lives in `session.lastAppliedSeq`, and a+ // terminal status - all `isSettledResearchRun` reads `lastEventSeq` for - comes with a+ // snapshot.+ const eventRun: ResearchRun = event.run ?? currentRun;const hydratedEvent: ResearchEvent = {...event,data: { ...event.data, run: eventRun },diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 274a07bfa91..d14785fd2b1 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -317,8 +317,11 @@ const SingleContent = memo(function SingleContent({useResearchRunStore.getState().sessions[openResearchRunId]?.run;if (openRun && openRun.threadId !== activeThreadId) closeResearchPanel();}, [activeThreadId, openResearchRunId, closeResearchPanel]);- const openResearchRun = useResearchRunStore((state) =>- openResearchRunId ? state.sessions[openResearchRunId]?.run : undefined,+ // A string, not the run: report deltas replace the run ~12x/s, and this owns the thread pane.+ const openResearchThreadId = useResearchRunStore((state) =>+ openResearchRunId+ ? state.sessions[openResearchRunId]?.run.threadId+ : undefined,);const artifactPanelRef = useRef<PanelImperativeHandle | null>(null);const hasInitializedArtifactPanelRef = useRef(false);@@ -329,8 +332,8 @@ const SingleContent = memo(function SingleContent({const [isArtifactSurfaceVisible, setIsArtifactSurfaceVisible] =useState(false);const researchMatchesThread = Boolean(- openResearchRun &&- openResearchRun.threadId === (threadId ?? activeThreadId),+ openResearchThreadId &&+ openResearchThreadId === (threadId ?? activeThreadId),);const showResearchPanel = researchMatchesThread && !isMobile;// Without a URL threadId the artifact must belong to the active thread.@@ -1958,8 +1961,12 @@ export function ChatPage({const latestResearchRunId = useResearchRunStore((state) =>activeThreadId ? state.latestRunByThreadId[activeThreadId] : undefined,);- const latestResearchRun = useResearchRunStore((state) =>- latestResearchRunId ? state.sessions[latestResearchRunId]?.run : undefined,+ // Status, not the run: this subscribes in ChatPage itself, so a run selector re-rendered the+ // whole page on every streamed research delta.+ const latestResearchRunStatus = useResearchRunStore((state) =>+ latestResearchRunId+ ? state.sessions[latestResearchRunId]?.run.status+ : undefined,);const openResearchPanel = useResearchRunStore((state) => state.openPanel);const openResearchRunId = useResearchRunStore((state) => state.openRunId);@@ -3482,30 +3489,32 @@ export function ChatPage({</TooltipContent></Tooltip>)}- {view.mode === "single" && latestResearchRun ? (+ {view.mode === "single" &&+ latestResearchRunId &&+ latestResearchRunStatus ? (<Tooltip><TooltipPrimitive.Trigger asChild={true}><buttontype="button"onClick={() => {- if (openResearchRunId === latestResearchRun.id) {+ if (openResearchRunId === latestResearchRunId) {closeResearchPanel();return;}setSettingsOpen(false);closeArtifactSurface();- openResearchPanel(latestResearchRun.id);+ openResearchPanel(latestResearchRunId);}}className="relative flex size-[30px] cursor-pointer items-center justify-center rounded-[10px] text-nav-fg transition-colors hover:bg-nav-surface-hover hover:text-black focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring dark:hover:text-white"aria-label="Open research activity"- aria-pressed={openResearchRunId === latestResearchRun.id}+ aria-pressed={openResearchRunId === latestResearchRunId}><HugeiconsIconicon={Telescope02Icon}className="size-icon"strokeWidth={1.75}/>- {!['completed', 'failed', 'cancelled'].includes(latestResearchRun.status) ? (+ {!['completed', 'failed', 'cancelled'].includes(latestResearchRunStatus) ? (<span className="absolute right-1 top-1 size-1.5 rounded-full bg-primary ring-2 ring-background" />) : null}</button>diff --git a/studio/frontend/src/features/chat/components/research-message.tsx b/studio/frontend/src/features/chat/components/research-message.tsxindex 8accb9ea5fe..7e9eb9943c5 100644--- a/studio/frontend/src/features/chat/components/research-message.tsx+++ b/studio/frontend/src/features/chat/components/research-message.tsx@@ -108,6 +108,7 @@ export function ResearchMessage(): ReactElement {<MarkdownPreviewmarkdown={run.report}className="max-h-none overflow-visible border-0 bg-transparent p-0 text-ui-15p5"+ defer={true}/><SourcesGroup sources={sources} allowRemoteIcons={false} /><DocumentSourcesGroup sources={documentSources} />diff --git a/studio/frontend/src/features/hub/catalog/model-readme.tsx b/studio/frontend/src/features/hub/catalog/model-readme.tsxindex 889b0113993..140abe3bf64 100644--- a/studio/frontend/src/features/hub/catalog/model-readme.tsx+++ b/studio/frontend/src/features/hub/catalog/model-readme.tsx@@ -6,6 +6,11 @@ import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";import { LruMap } from "@/features/hub/lib/lru-map";import { isHuggingFaceOffline } from "@/features/hub/lib/network";import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";+import {+ type MarkdownPluginNeeds,+ markdownPluginNeeds,+} from "@/lib/markdown-plugins";+import { scheduleIdleTask } from "@/lib/schedule-idle-task";import { cn } from "@/lib/utils";import { confirmExternalLink } from "../stores/external-link-confirm";import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";@@ -63,8 +68,6 @@ const README_ALLOWED_TAGS: NonNullable<track: ["src", "kind", "srclang", "label", "default"],};-const READMEX_NEEDS_MATH = /\$\$|\\\(|\\\[/;-const READMEX_NEEDS_MERMAID = /```mermaid\b/;const README_RENDER_CHAR_LIMIT = 120_000;const README_CACHE_TTL_MS = 60_000;const README_TRUNCATED_NOTICE =@@ -254,39 +257,6 @@ function isMissingReadmeError(error: string): boolean {return /^No (dataset|model) card available\.$/.test(error);}-function scheduleIdleTask(callback: () => void, timeout = 250): () => void {- let canceled = false;- const run = () => {- if (!canceled) callback();- };-- if (typeof window === "undefined") {- run();- return () => {- canceled = true;- };- }-- const idleWindow = window as Window & {- requestIdleCallback?: Window["requestIdleCallback"];- cancelIdleCallback?: Window["cancelIdleCallback"];- };-- if (idleWindow.requestIdleCallback && idleWindow.cancelIdleCallback) {- const handle = idleWindow.requestIdleCallback(run, { timeout });- return () => {- canceled = true;- idleWindow.cancelIdleCallback?.(handle);- };- }-- const handle = globalThis.setTimeout(run, Math.min(timeout, 120));- return () => {- canceled = true;- globalThis.clearTimeout(handle);- };-}-function ReadmePlaceholder({kind,message,@@ -366,10 +336,7 @@ async function loadReadmeFromCache({}}-function loadPlugins(needs: {- math: boolean;- mermaid: boolean;-}): ReadmePlugins {+function loadPlugins(needs: MarkdownPluginNeeds): ReadmePlugins {const plugins: ReadmePlugins = { code: streamdownCode };if (needs.math) plugins.math = streamdownMath;if (needs.mermaid) plugins.mermaid = streamdownMermaid;@@ -507,12 +474,7 @@ export function ModelReadme({});};const cancelIdle = scheduleIdleTask(() => {- applyPlugins(- loadPlugins({- math: READMEX_NEEDS_MATH.test(body),- mermaid: READMEX_NEEDS_MERMAID.test(body),- }),- );+ applyPlugins(loadPlugins(markdownPluginNeeds(body)));}, 400);return () => {canceled = true;diff --git a/studio/frontend/src/lib/markdown-plugins.ts b/studio/frontend/src/lib/markdown-plugins.tsnew file mode 100644index 00000000000..7a88d5dfe60--- /dev/null+++ b/studio/frontend/src/lib/markdown-plugins.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Which Streamdown plugins a document actually needs.+ *+ * Math and mermaid over a document with neither still cost a pass per node on the main thread,+ * in the one commit that lands the finished report - where issue #8483 froze. Detection lives+ * here so the model card and report renderers share one rule, testable without a DOM.+ */++/** `$$…$$`, `\(…\)` and `\[…\]`; single `$` is too common in prose to treat as math. */+const NEEDS_MATH = /\$\$|\\\(|\\\[/;+// CommonMark fences with three or more backticks or tildes, and both reach the renderer as lang+// "mermaid", so backticks alone would render a tilde-fenced diagram as a plain code block. Not+// anchored to the line start, so a fence nested in a list item still counts: over-matching costs+// one unused plugin, under-matching costs a diagram.+const NEEDS_MERMAID = /(?:`{3,}|~{3,})[ \t]*mermaid\b/;++/** Past this a document stays plain monospace: shiki is not worth the main-thread time. */+export const MAX_HIGHLIGHT_CHARS = 20_000;++export interface MarkdownPluginNeeds {+ math: boolean;+ mermaid: boolean;+ code: boolean;+}++export function markdownPluginNeeds(markdown: string): MarkdownPluginNeeds {+ return {+ math: NEEDS_MATH.test(markdown),+ mermaid: NEEDS_MERMAID.test(markdown),+ code: markdown.length <= MAX_HIGHLIGHT_CHARS,+ };+}diff --git a/studio/frontend/src/lib/schedule-idle-task.ts b/studio/frontend/src/lib/schedule-idle-task.tsnew file mode 100644index 00000000000..63dcb760f96--- /dev/null+++ b/studio/frontend/src/lib/schedule-idle-task.ts@@ -0,0 +1,43 @@+// 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 `callback` once the main thread is idle, or after `timeout` at the latest; returns a+ * canceller. Falls back to setTimeout without requestIdleCallback (Safari, the WebKitGTK webview+ * the desktop app embeds on Linux), and runs synchronously with no window.+ */+export function scheduleIdleTask(+ callback: () => void,+ timeout = 250,+): () => void {+ let canceled = false;+ const run = () => {+ if (!canceled) callback();+ };++ if (typeof window === "undefined") {+ run();+ return () => {+ canceled = true;+ };+ }++ const idleWindow = window as Window & {+ requestIdleCallback?: Window["requestIdleCallback"];+ cancelIdleCallback?: Window["cancelIdleCallback"];+ };++ if (idleWindow.requestIdleCallback && idleWindow.cancelIdleCallback) {+ const handle = idleWindow.requestIdleCallback(run, { timeout });+ return () => {+ canceled = true;+ idleWindow.cancelIdleCallback?.(handle);+ };+ }++ const handle = globalThis.setTimeout(run, Math.min(timeout, 120));+ return () => {+ canceled = true;+ globalThis.clearTimeout(handle);+ };+}diff --git a/studio/frontend/tests/research-render-budget.test.ts b/studio/frontend/tests/research-render-budget.test.tsnew file mode 100644index 00000000000..3235b3c44a1--- /dev/null+++ b/studio/frontend/tests/research-render-budget.test.ts@@ -0,0 +1,116 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// #8483: the desktop app froze during a deep research run. Two costs only show under a real+// stream, so they are pinned at the source: what run-carrying components subscribe to, and what+// the finished report's markdown commit signs up for. Like drag-costs-no-render.test.ts: assert+// the cheap path, assert the expensive one is gone.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { markdownPluginNeeds, MAX_HIGHLIGHT_CHARS } from "../src/lib/markdown-plugins.ts";++function source(path: string): string {+ return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");+}++test("no research subscriber selects the whole run object", () => {+ // Each re-rendered its subtree on every streamed delta; thread.tsx's useThreadResearchActive+ // was already correct and is the shape the others now follow.+ for (const path of [+ "features/chat/chat-page.tsx",+ "components/assistant-ui/thread.tsx",+ ]) {+ const text = source(path);+ assert.doesNotMatch(+ text,+ /state\.sessions\[[^\]]+\]\?\.run;/,+ `${path} selects a run object out of the research store`,+ );+ assert.doesNotMatch(+ text,+ /return runId \? state\.sessions\[runId\]\?\.run : undefined;/,+ `${path} selects a run object out of the research store`,+ );+ }+});++test("chat-page derives the research pane from strings", () => {+ const page = source("features/chat/chat-page.tsx");+ assert.match(page, /state\.sessions\[openResearchRunId\]\?\.run\.threadId/);+ assert.match(page, /state\.sessions\[latestResearchRunId\]\?\.run\.status/);+});++test("Thread is memoized", () => {+ const thread = source("components/assistant-ui/thread.tsx");+ assert.match(thread, /export const Thread: FC<\{[^}]*\}> = memo\(/s);+ assert.match(thread, /Thread\.displayName = "Thread";/);+});++test("the report renderer is deferred and its plugins are conditional", () => {+ const preview = source("components/markdown/markdown-preview.tsx");+ assert.match(preview, /markdownPluginNeeds\(markdown\)/);+ assert.match(preview, /scheduleIdleTask\(\(\) => setReadyMarkdown\(markdown\), 200\)/);+ // The old path: all three plugins, always, in one synchronous commit.+ assert.doesNotMatch(preview, /const MARKDOWN_PLUGINS = \{ code, math, mermaid \}/);+ const message = source("features/chat/components/research-message.tsx");+ assert.match(message, /markdown=\{run\.report\}[\s\S]*?defer=\{true\}/);+});++test("deferred readiness belongs to a markdown value, not to the component", () => {+ // Blanking readiness from a passive effect lands one commit late, so the parse is paid twice.+ // Measured on a 202KB report: a wasted 576ms parse, then a second one, ~1.11s blocked against+ // ~0.66s once readiness is derived during render.+ const preview = source("components/markdown/markdown-preview.tsx");+ assert.match(preview, /const ready = !defer \|\| readyMarkdown === markdown;/);+ assert.match(preview, /scheduleIdleTask\(\(\) => setReadyMarkdown\(markdown\), 200\)/);+ assert.doesNotMatch(preview, /useState\(!defer\)/);+ assert.doesNotMatch(preview, /setReady\(false\)/);+ assert.match(preview, /\{ready \? \(\s*<Streamdown/);+});++test("plugin needs follow the document", () => {+ assert.deepEqual(markdownPluginNeeds("plain prose with `code` spans"), {+ math: false,+ mermaid: false,+ code: true,+ });+ assert.equal(markdownPluginNeeds("a $$x^2$$ b").math, true);+ assert.equal(markdownPluginNeeds("\\(x\\)").math, true);+ assert.equal(markdownPluginNeeds("\\[x\\]").math, true);+ // A lone $ is too common in prose (prices, shell prompts) to pull KaTeX in for.+ assert.equal(markdownPluginNeeds("costs $5 to run").math, false);+ // Nor a balanced pair: these callers install `@streamdown/math`'s bare export, which pins+ // singleDollarTextMath to false, so `$x^2$` renders literally with the plugin loaded too.+ // (`markdown-text.tsx` enables it, but does not use this detector.) If that changes, NEEDS_MATH+ // must change with it - and "costs $5 and $10" is why a balanced-pair regex is not the answer.+ assert.equal(markdownPluginNeeds("the area is $x^2$ per unit").math, false);+ assert.match(+ source("components/markdown/markdown-preview.tsx"),+ /import \{ math \} from "@streamdown\/math";/,+ );+ assert.equal(markdownPluginNeeds("```mermaid\ngraph TD;\n```").mermaid, true);+ assert.equal(markdownPluginNeeds("```python\npass\n```").mermaid, false);+ // CommonMark fences with three or more backticks *or* tildes, and allows longer fences. All of+ // these reach the renderer as lang "mermaid".+ assert.equal(markdownPluginNeeds("~~~mermaid\ngraph TD;\n~~~").mermaid, true);+ assert.equal(markdownPluginNeeds("````mermaid\ngraph TD;\n````").mermaid, true);+ assert.equal(markdownPluginNeeds("~~~~mermaid\ngraph TD;\n~~~~").mermaid, true);+ assert.equal(markdownPluginNeeds("~~~ mermaid\ngraph TD;\n~~~").mermaid, true);+ assert.equal(markdownPluginNeeds("~~~python\npass\n~~~").mermaid, false);+ // Two tildes is strikethrough, not a fence.+ assert.equal(markdownPluginNeeds("~~mermaid~~ is a tool").mermaid, false);+});++test("highlighting is capped, and the cap is one constant", () => {+ assert.equal(markdownPluginNeeds("x".repeat(MAX_HIGHLIGHT_CHARS)).code, true);+ assert.equal(+ markdownPluginNeeds("x".repeat(MAX_HIGHLIGHT_CHARS + 1)).code,+ false,+ );+ const cell = source("components/assistant-ui/tool-code-cell.tsx");+ assert.match(cell, /import \{ MAX_HIGHLIGHT_CHARS \} from "@\/lib\/markdown-plugins";/);+ assert.doesNotMatch(cell, /const MAX_HIGHLIGHT_CHARS = /);+});diff --git a/studio/frontend/tests/research-run-identity.test.ts b/studio/frontend/tests/research-run-identity.test.tsnew file mode 100644index 00000000000..cd914c268b2--- /dev/null+++ b/studio/frontend/tests/research-run-identity.test.ts@@ -0,0 +1,165 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// #8483: every delta event minted a new run object, so every component selecting the run+// re-rendered ~12x/s for the whole synthesis - including ChatPage, which owns the thread pane.+// The backend omits the run from those events by design (_DELTA_ONLY_EVENTS in+// studio/backend/routes/research_runs.py); the frontend must not reinvent it.++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++register("./helpers/settings-api-resolver.mjs", import.meta.url);+registerBundlerResolver();+installLocalStorageFake();++const { followResearchRun } = await import(+ "../src/features/chat/api/research-api.ts"+);++type AnyRecord = Record<string, unknown>;++const RUN_ID = "run-identity";++function snapshot(overrides: AnyRecord = {}): AnyRecord {+ return {+ id: RUN_ID,+ thread_id: "thread-1",+ user_message_id: "user-1",+ status: "running",+ plan: null,+ plan_revision: 0,+ plan_hash: null,+ steps: [],+ sources: [],+ last_event_seq: 0,+ created_at: 1,+ updated_at: 1,+ ...overrides,+ };+}++/** One SSE frame in the shape routes/research_runs.py writes. */+function frame(id: number, event: string, data: AnyRecord): string {+ return `id: ${id}\nevent: ${event}\ndata: ${JSON.stringify(data)}\n\n`;+}++function sseResponse(frames: string[]): Response {+ const encoder = new TextEncoder();+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ for (const chunk of frames) controller.enqueue(encoder.encode(chunk));+ controller.close();+ },+ });+ return new Response(stream, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+}++function stubFetch(frames: string[], finalSnapshot: AnyRecord): () => void {+ const original = globalThis.fetch;+ let streamed = false;+ globalThis.fetch = (async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("/events")) {+ if (streamed) {+ // A second connect would loop forever; hand back an empty stream instead.+ return sseResponse([]);+ }+ streamed = true;+ return sseResponse(frames);+ }+ return new Response(JSON.stringify(finalSnapshot), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ }) as typeof globalThis.fetch;+ return () => {+ globalThis.fetch = original;+ };+}++test("delta-only events reuse the run object they were given", async () => {+ const terminal = snapshot({+ status: "completed",+ last_event_seq: 4,+ updated_at: 9,+ report: "done",+ });+ const restore = stubFetch(+ [+ frame(1, "reasoning.updated", {+ created_at: 2,+ call_id: "call-1",+ reasoning_delta: "a",+ }),+ frame(2, "report.updated", { created_at: 3, length: 32, delta: 32 }),+ frame(3, "reasoning.updated", {+ created_at: 4,+ call_id: "call-1",+ reasoning_delta: "b",+ }),+ frame(4, "run.completed", { created_at: 9, attempt: 0, run: terminal }),+ ],+ terminal,+ );+ try {+ const runs: unknown[] = [];+ for await (const update of followResearchRun(RUN_ID, {+ initialRun: snapshot() as never,+ })) {+ runs.push(update.run);+ }+ // snapshot, three deltas, terminal.+ assert.equal(runs.length, 5);+ assert.equal(runs[1], runs[0], "first delta minted a new run object");+ assert.equal(runs[2], runs[0], "second delta minted a new run object");+ assert.equal(runs[3], runs[0], "third delta minted a new run object");+ assert.notEqual(+ runs[4],+ runs[0],+ "the terminal event carries its own snapshot and must replace the run",+ );+ assert.equal(+ (runs[4] as AnyRecord).status,+ "completed",+ "the terminal snapshot must still be applied",+ );+ } finally {+ restore();+ }+});++test("a run carried by an event still replaces the held run", async () => {+ const midway = snapshot({ status: "running", last_event_seq: 1, updated_at: 5 });+ const terminal = snapshot({ status: "completed", last_event_seq: 2, updated_at: 9 });+ const restore = stubFetch(+ [+ frame(1, "phase.started", { created_at: 5, phase: "synthesis", run: midway }),+ frame(2, "run.completed", { created_at: 9, attempt: 0, run: terminal }),+ ],+ terminal,+ );+ try {+ const runs: AnyRecord[] = [];+ for await (const update of followResearchRun(RUN_ID, {+ initialRun: snapshot() as never,+ })) {+ runs.push(update.run as unknown as AnyRecord);+ }+ assert.equal(runs.length, 3);+ assert.notEqual(runs[1], runs[0]);+ assert.equal(runs[1].updatedAt, 5);+ assert.equal(runs[2].status, "completed");+ } finally {+ restore();+ }+});diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.pyindex 1dc861d8348..e89e032652f 100644--- a/tests/studio/test_deep_research_frontend_contract.py+++ b/tests/studio/test_deep_research_frontend_contract.py@@ -299,7 +299,9 @@ def test_research_stop_is_prompt_only_and_deduplicated() -> None:activity = source("features/chat/components/research-activity-panel.tsx")assert "stoppingResearchRunIdRef" in thread- assert 'activeResearchRun.status === "cancelling"' in thread+ # The composer selects the run status, not the run object, so a streamed research delta+ # does not re-render it. The cancelling guard reads that status.+ assert 'activeResearchRunStatus === "cancelling"' in threadassert 'aria-label={researchStopping ? "Stopping research"' in threadassert "cancelResearchRun" not in activityassert "Stop research" not in activity