Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Chat: stop a keystroke in the composer costing one pass over the thread (#9054)

Daniel Han0f62511cd726
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 58f46d2ab1b..4d963ace181 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -25,8 +25,10 @@ import { createMathPlugin } from "@streamdown/math";
import { mermaid } from "@streamdown/mermaid";
import {
type ComponentProps,
+ createContext,
memo,
useCallback,
+ useContext,
useEffect,
useMemo,
useRef,
@@ -293,6 +295,21 @@ function useAnimationFreeBlockProps(props: BlockProps): BlockProps {
} satisfies BlockProps;
}
+/**
+ * Whether this message carries a renderable render_html tool part, asked once per message part
+ * instead of once per markdown block.
+ *
+ * The value belongs to the MESSAGE, but the block component is mounted per block, so subscribing
+ * there minted a subscription per block (800 of 10,193 on the 300K-character heavy thread), each
+ * re-scanning `message.parts` on every store update -- and every keystroke is a store update.
+ * One subscription in MarkdownTextImpl plus a context read gives the same blocks the same answer.
+ *
+ * `false` is the right default for a block rendered outside a message part (nothing does today):
+ * no render_html part is visible, which is what the artifact collapse below assumes absent
+ * evidence.
+ */
+const RenderHtmlToolPresenceContext = createContext(false);
+
// Collapse a full-HTML answer in place into an artifact card. Diffusion keeps the
// raw code visible instead (the trailing MessageHtmlArtifacts appends its card).
function StreamdownBlockContent(props: BlockProps) {
@@ -302,8 +319,8 @@ function StreamdownBlockContent(props: BlockProps) {
(state.artifactsEnabled || state.collapseHtmlArtifacts) &&
!state.loadedIsDiffusion,
);
- const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>
- message.parts.some(isRenderableRenderHtmlToolPart),
+ const messageHasRenderableRenderHtmlTool = useContext(
+ RenderHtmlToolPresenceContext,
);
const hasMermaidFence = props.content.includes("```mermaid");
const mermaidSource = getMermaidSource(props.content);
@@ -463,6 +480,10 @@ const MarkdownTextImpl = () => {
// 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),
+ );
const isStreaming = status.type === "running";
const displayText = useCoalescedStreamingText(text, isStreaming, messageId);
const processedText = useMemo(
@@ -490,24 +511,28 @@ const MarkdownTextImpl = () => {
}
return (
- <div data-status={status.type} className="min-w-0 max-w-full">
- <Streamdown
- key={`${messageId}:${incrementalCache.renderGeneration}`}
- mode="streaming"
- parseIncompleteMarkdown={!incrementalRender}
- parseMarkdownIntoBlocksFn={incrementalRender?.parseMarkdownIntoBlocks}
- isAnimating={isStreaming}
- animated={STREAMDOWN_IMMEDIATE_UPDATES}
- plugins={STREAMDOWN_PLUGINS}
- components={STREAMDOWN_COMPONENTS}
- urlTransform={safeMarkdownUrl}
- controls={STREAMDOWN_CONTROLS}
- shikiTheme={STREAMDOWN_SHIKI_THEME}
- BlockComponent={StreamdownBlock}
- >
- {incrementalRender?.markdown ?? processedText}
- </Streamdown>
- </div>
+ <RenderHtmlToolPresenceContext.Provider
+ value={messageHasRenderableRenderHtmlTool}
+ >
+ <div data-status={status.type} className="min-w-0 max-w-full">
+ <Streamdown
+ key={`${messageId}:${incrementalCache.renderGeneration}`}
+ mode="streaming"
+ parseIncompleteMarkdown={!incrementalRender}
+ parseMarkdownIntoBlocksFn={incrementalRender?.parseMarkdownIntoBlocks}
+ isAnimating={isStreaming}
+ animated={STREAMDOWN_IMMEDIATE_UPDATES}
+ plugins={STREAMDOWN_PLUGINS}
+ components={STREAMDOWN_COMPONENTS}
+ urlTransform={safeMarkdownUrl}
+ controls={STREAMDOWN_CONTROLS}
+ shikiTheme={STREAMDOWN_SHIKI_THEME}
+ BlockComponent={StreamdownBlock}
+ >
+ {incrementalRender?.markdown ?? processedText}
+ </Streamdown>
+ </div>
+ </RenderHtmlToolPresenceContext.Provider>
);
};
diff --git a/studio/frontend/src/components/assistant-ui/thread-research-presence.ts b/studio/frontend/src/components/assistant-ui/thread-research-presence.ts
new file mode 100644
index 00000000000..32a34d73e85
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/thread-research-presence.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
+
+/**
+ * Whether a thread already holds a research answer, asked once per message array rather than once
+ * per keystroke.
+ *
+ * The composer asks this to decide whether deep research is still offerable, inside a
+ * `useAuiState` selector -- and `useAuiState` is `useSyncExternalStore` with the selector AS
+ * getSnapshot, so every store write runs every selector. The composer is controlled off store
+ * state, so every character typed is a store write, and this scan walked every message through
+ * the state proxy per keystroke (React may even run getSnapshot twice before commit) for an
+ * answer that never changed while typing.
+ *
+ * assistant-ui rebuilds the message array on every repository change, so the array identity is
+ * exactly the revision the answer depends on. Keying on it makes typing O(1) and keeps the answer
+ * identical to the scan it replaces, including when a research reply's metadata arrives later:
+ * that arrival replaces the array.
+ *
+ * Two cache misses, both perf-only and neither worse than the old unconditional scan: a streaming
+ * reply rebuilds the array per token, and `MessageRepository.getMessages(headId)` for an explicit
+ * non-head branch builds a fresh array per call, so a caller reading a branch head instead of
+ * `thread.messages` would miss permanently.
+ *
+ * Weak, so a dead thread takes its entry with it. Sibling of research-reply-owners.ts, which
+ * answers the per-message ownership question the same way; separate because one cache holding
+ * both answers off the same revision would hand a caller the other's.
+ */
+
+export type ResearchPresenceMessage = { metadata?: unknown };
+
+const presenceByMessages = new WeakMap<object, boolean>();
+
+/** Whether any message carries `metadata.custom.researchRunId` as a string. */
+export function messageHasResearchRunId(
+ message: ResearchPresenceMessage,
+): boolean {
+ const custom = (
+ message.metadata as { custom?: { researchRunId?: unknown } } | undefined
+ )?.custom;
+ return typeof custom?.researchRunId === "string";
+}
+
+/** @param messages the thread's message array, used as the revision key. */
+export function threadHasResearchMessage(
+ messages: readonly ResearchPresenceMessage[],
+): boolean {
+ const known = presenceByMessages.get(messages);
+ if (known !== undefined) {
+ return known;
+ }
+ const answer = messages.some(messageHasResearchRunId);
+ presenceByMessages.set(messages, answer);
+ return answer;
+}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index c4c856b007d..4d4a53af86f 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -17,6 +17,7 @@ import {
MessageResponseModelBadge,
} from "@/components/assistant-ui/message-response-details-sheet";
import { MessageTiming } from "@/components/assistant-ui/message-timing";
+import { threadHasResearchMessage } from "@/components/assistant-ui/thread-research-presence";
import { Reasoning, ReasoningGroup } from "@/components/assistant-ui/reasoning";
import { RagSourcesGroup } from "@/components/assistant-ui/rag-sources";
import { researchReplyOwners } from "@/components/assistant-ui/research-reply-owners";
@@ -2214,14 +2215,7 @@ const Composer: FC<{
);
});
const hasResearchMessage = useAuiState(({ thread }) =>
- thread.messages.some((message) => {
- const custom = (
- message.metadata as
- | { custom?: { researchRunId?: unknown } }
- | undefined
- )?.custom;
- return typeof custom?.researchRunId === "string";
- }),
+ threadHasResearchMessage(thread.messages),
);
const researchUsed = researchThreadClaimed || hasResearchMessage;
const effectiveDeepResearchEnabled = deepResearchEnabled && !researchUsed;
@@ -6264,6 +6258,23 @@ function assistantMessageText(content: readonly unknown[] | undefined): string {
* Retry keeps its old meaning: drop the partial and start over.
*/
const ContinueMessageBar: FC = () => {
+ // One subscription, not ten, on every message that is not the newest.
+ //
+ // The bar mounts under every assistant message and returns null unless it is the last, but the
+ // ten `useAuiState` calls below ran first, each a subscription whose selector re-runs on EVERY
+ // store update -- one per character typed (220 messages, 300K characters: 10,193 subscriptions,
+ // 10,258 selector runs per keystroke).
+ //
+ // `isLast` is the same condition the body below already gates on, asked before the work rather
+ // than after it, so nothing that used to render stops rendering.
+ const isLast = useAuiState(({ message }) => message.isLast);
+ if (!isLast) {
+ return null;
+ }
+ return <ContinueMessageBarForLastMessage />;
+};
+
+const ContinueMessageBarForLastMessage: FC = () => {
const aui = useAui();
const messageId = useAuiState(({ message }) => message.id);
const isLast = useAuiState(({ message }) => message.isLast);
diff --git a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
new file mode 100644
index 00000000000..c47c502d765
--- /dev/null
+++ b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
@@ -0,0 +1,121 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Typing one character in the composer costs work proportional to the whole thread, none of it
+// rendering.
+//
+// assistant-ui has ONE notification manager. `useAuiState` subscribes to it through
+// `useSyncExternalStore` with the selector AS getSnapshot, so a single store write runs every
+// selector in the tree, and writing a character calls `composer.setText`. Measured on a synthetic
+// heavy thread with the manager instrumented to count live subscriptions and selector runs:
+//
+// 20 messages 955 subscriptions 1,020 selector runs per keystroke 1.8ms
+// 80 messages 3,726 subscriptions 3,791 selector runs per keystroke 7.2ms
+// 220 messages 10,193 subscriptions 10,258 selector runs per keystroke 19.6ms
+//
+// Layout and style are flat across the same range, so the fan-out, not the DOM, is what grows.
+//
+// The two seams below stop a subscription being minted per markdown BLOCK and per non-newest
+// message. Neither shows in the output -- undo either and the thread renders identically and
+// every other test passes -- so, like chat-autoscroll-frame-budget.test.ts and
+// drag-costs-no-render.test.ts, the wiring is pinned at the source. The counts above are the
+// motivation, not an assertion: a regression in them alone would not fail these source-shape
+// checks.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+function source(path: string): string {
+ return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");
+}
+
+const markdown = source("components/assistant-ui/markdown-text.tsx");
+const thread = source("components/assistant-ui/thread.tsx");
+
+/** The body of the named function or component declaration, up to its closing brace. */
+function body(text: string, start: string, terminator = "\n}"): string {
+ const index = text.indexOf(start);
+ assert.notEqual(index, -1, `${start} is gone; this test needs rewriting`);
+ const rest = text.slice(index + start.length);
+ const end = rest.indexOf(terminator);
+ assert.notEqual(end, -1, `${start} has no closing brace`);
+ return rest.slice(0, end);
+}
+
+test("a markdown block reads the render_html presence from context, not the store", () => {
+ const block = body(
+ markdown,
+ "function StreamdownBlockContent(props: BlockProps) {",
+ );
+ assert.match(block, /useContext\(\s*RenderHtmlToolPresenceContext,?\s*\)/);
+ // Mounted once per markdown block: 800 of the 10,193 subscriptions at 300K characters, each
+ // re-scanning message.parts per keystroke.
+ assert.doesNotMatch(
+ block,
+ /useAuiState\(/,
+ "a markdown block subscribes to the assistant store, so every block pays per keystroke",
+ );
+});
+
+test("the render_html scan happens once per message part, above the blocks", () => {
+ const impl = body(markdown, "const MarkdownTextImpl = () => {", "\n};");
+ 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,
+ /<RenderHtmlToolPresenceContext\.Provider\s+value=\{messageHasRenderableRenderHtmlTool\}/,
+ );
+});
+
+test("the continue bar subscribes once on a message that is not the newest", () => {
+ const gate = body(thread, "const ContinueMessageBar: FC = () => {", "\n};");
+ // Exactly one subscription before the gate, and it is the gate's own condition.
+ const subscriptions = gate.match(/useAuiState\(/g) ?? [];
+ assert.equal(
+ subscriptions.length,
+ 1,
+ "the continue bar subscribes more than once before it knows the message is the newest",
+ );
+ assert.match(gate, /useAuiState\(\(\{ message \}\) => message\.isLast\)/);
+ assert.match(gate, /if \(!isLast\) \{\s*return null;\s*\}/);
+ assert.match(gate, /<ContinueMessageBarForLastMessage \/>/);
+});
+
+test("the composer asks the thread-wide research question through the cache", () => {
+ // The composer's own subscription walked every message per keystroke. The answer's semantics
+ // live in thread-research-presence.test.ts; this pins the composer as the caller, since an
+ // orphaned helper would leave the scan where it was.
+ assert.match(
+ thread,
+ /useAuiState\(\(\{ thread \}\) =>\s*threadHasResearchMessage\(thread\.messages\),?\s*\)/,
+ );
+ assert.doesNotMatch(
+ thread,
+ /useAuiState\(\(\{ thread \}\) =>\s*thread\.messages\.some\(/,
+ "the composer scans every message inside a selector again",
+ );
+});
+
+test("the newest message still gets the whole continue bar", () => {
+ // The gate must delegate rather than have deleted the work: the bar Max Tokens, Stop and a
+ // dropped stream rely on is the one below it.
+ const full = body(
+ thread,
+ "const ContinueMessageBarForLastMessage: FC = () => {",
+ "\n};",
+ );
+ for (const marker of [
+ /useAuiState\(\(\{ message \}\) => message\.status\)/,
+ /useAuiState\(\(\{ message \}\) => message\.metadata\)/,
+ /assistantMessageText\(message\.content\)/,
+ /isContinuableContent\(message\.content\)/,
+ /findLatestUserAudioBase64\(thread\.messages, false\)/,
+ /modeAllowsContinuation\(\{/,
+ ]) {
+ assert.match(full, marker);
+ }
+});
diff --git a/studio/frontend/tests/thread-research-presence.test.ts b/studio/frontend/tests/thread-research-presence.test.ts
new file mode 100644
index 00000000000..6dfd3822a4a
--- /dev/null
+++ b/studio/frontend/tests/thread-research-presence.test.ts
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The composer's "has this thread used research already" answer, which gates whether deep
+// research is still offerable. It is asked inside a useAuiState selector, so once per store
+// write, and a keystroke IS a store write: before this cache the composer walked all 220 messages
+// of the heavy-thread fixture per character typed.
+//
+// Semantics first, cache second: a memoization bug here silently turns deep research back on in a
+// thread that already used it, or off in one that has not.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ messageHasResearchRunId,
+ threadHasResearchMessage,
+} from "../src/components/assistant-ui/thread-research-presence.ts";
+
+const withRun = (id: unknown) => ({
+ metadata: { custom: { researchRunId: id } },
+});
+
+test("a thread with a research reply anywhere in it answers true", () => {
+ assert.equal(threadHasResearchMessage([{}, withRun("run_1"), {}]), true);
+ assert.equal(threadHasResearchMessage([withRun("run_1")]), true);
+});
+
+test("a thread with no research reply answers false", () => {
+ assert.equal(threadHasResearchMessage([]), false);
+ assert.equal(threadHasResearchMessage([{}, { metadata: {} }]), false);
+ assert.equal(threadHasResearchMessage([{ metadata: { custom: {} } }]), false);
+ assert.equal(threadHasResearchMessage([{ metadata: undefined }]), false);
+});
+
+test("only a string run id counts, which is what the composer's gate meant", () => {
+ // A non-string run id is how a half-written metadata blob shows up; counting it would switch
+ // deep research off in a thread that never used it.
+ for (const id of [undefined, null, 0, 1, true, {}, ["run_1"]]) {
+ assert.equal(messageHasResearchRunId(withRun(id)), false, String(id));
+ assert.equal(threadHasResearchMessage([withRun(id)]), false, String(id));
+ }
+ assert.equal(messageHasResearchRunId(withRun("")), true);
+});
+
+test("the answer is cached on the message array, not recomputed per call", () => {
+ let reads = 0;
+ const counting = [
+ {
+ get metadata() {
+ reads += 1;
+ return { custom: { researchRunId: "run_1" } };
+ },
+ },
+ ];
+ assert.equal(threadHasResearchMessage(counting), true);
+ const afterFirst = reads;
+ assert.ok(afterFirst > 0, "the first call has to read the messages");
+ for (let i = 0; i < 50; i += 1) {
+ assert.equal(threadHasResearchMessage(counting), true);
+ }
+ assert.equal(
+ reads,
+ afterFirst,
+ "the scan runs again on an unchanged message array",
+ );
+});
+
+test("a new message array is a new answer", () => {
+ // assistant-ui rebuilds the array on every repository change, which is why it is the key: a
+ // cache outliving the array would answer for the previous thread.
+ const before = [{ metadata: {} }];
+ assert.equal(threadHasResearchMessage(before), false);
+ const after = [...before, withRun("run_1")];
+ assert.equal(threadHasResearchMessage(after), true);
+ // The old array still answers what it did, rather than being invalidated by the new one.
+ assert.equal(threadHasResearchMessage(before), false);
+});