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.

Studio: keep typing and streaming fast in long chats (#13059)

Daniel Han63988fd030bf
diff --git a/studio/frontend/smoke-thread-weight-main.tsx b/studio/frontend/smoke-thread-weight-main.tsx
index 6a0f501b928..b26f84dc01d 100644
--- a/studio/frontend/smoke-thread-weight-main.tsx
+++ b/studio/frontend/smoke-thread-weight-main.tsx
@@ -21,8 +21,11 @@ import {
AssistantRuntimeProvider,
type ChatModelAdapter,
ExportedMessageRepository,
+ SimpleImageAttachmentAdapter,
type ThreadMessageLike,
useAui,
+ unstable_useRemoteThreadListRuntime,
+ type unstable_RemoteThreadListAdapter,
useLocalRuntime,
} from "@assistant-ui/react";
import {
@@ -112,7 +115,42 @@ function userMarkdown(index: number): string {
* `"all"` makes every reply plain; omitting it keeps the default fenced body everywhere, so
* the existing weight measurements are untouched.
*/
-type SeedOptions = { plainAssistants?: readonly number[] | "all" };
+type SeedOptions = {
+ plainAssistants?: readonly number[] | "all";
+ /** `rounds` x reasoning, tool call, answer per reply; truncation every `compactionEvery`th. */
+ agent?: { rounds: number; compactionEvery?: number };
+};
+
+const AGENT_TOOLS = ["web_search", "terminal", "python"] as const;
+
+function agentContent(index: number, rounds: number) {
+ const parts: Exclude<ThreadMessageLike["content"], string>[number][] = [];
+ for (let round = 0; round < rounds; round++) {
+ const tag = `${index}_${round}`;
+ const toolName = AGENT_TOOLS[(index + round) % AGENT_TOOLS.length];
+ const args: Record<string, string> =
+ toolName === "web_search"
+ ? { query: `step ${tag} reference for the scheduler buffer` }
+ : { code: `print("step ${tag}")` };
+ parts.push({
+ type: "reasoning" as const,
+ text: `Round ${tag}. ${PROSE} ${CLOSING}`,
+ });
+ parts.push({
+ type: "tool-call" as const,
+ toolCallId: `call_${tag}`,
+ toolName,
+ args,
+ argsText: JSON.stringify(args),
+ result: `Result ${tag}. ${PROSE}\n${PROSE}\n${CLOSING}`,
+ });
+ parts.push({
+ type: "text" as const,
+ text: `Answer ${tag}. ${PROSE}\n\n- first item ${tag}\n- second item ${tag}`,
+ });
+ }
+ return parts;
+}
function isPlain(assistantOrdinal: number, options: SeedOptions | undefined): boolean {
const plain = options?.plainAssistants;
@@ -126,32 +164,71 @@ function buildMessages(
count: number,
options?: SeedOptions,
): ThreadMessageLike[] {
- return Array.from({ length: count }, (_, index) =>
- index % 2 === 0
- ? {
- role: "user" as const,
- content: [{ type: "text" as const, text: userMarkdown(index) }],
- }
- : {
- role: "assistant" as const,
- content: [
- {
- type: "text" as const,
- text: isPlain((index - 1) / 2, options)
- ? plainAssistantMarkdown(index)
- : assistantMarkdown(index),
- },
- ],
+ const agent = options?.agent;
+ return Array.from({ length: count }, (_, index): ThreadMessageLike => {
+ if (index % 2 === 0) {
+ return {
+ role: "user" as const,
+ content: [{ type: "text" as const, text: userMarkdown(index) }],
+ };
+ }
+ if (agent) {
+ const ordinal = (index - 1) / 2;
+ const every = agent.compactionEvery ?? 0;
+ const compacted = every > 0 && ordinal > 0 && ordinal % every === 0;
+ return {
+ role: "assistant" as const,
+ content: agentContent(index, agent.rounds),
+ ...(compacted
+ ? {
+ metadata: {
+ custom: {
+ contextTruncation: {
+ dropped_messages: Math.max(1, index - 4),
+ boundary_messages: Math.max(1, index - 4),
+ fits: true,
+ },
+ },
+ },
+ }
+ : {}),
+ };
+ }
+ return {
+ role: "assistant" as const,
+ content: [
+ {
+ type: "text" as const,
+ text: isPlain((index - 1) / 2, options)
+ ? plainAssistantMarkdown(index)
+ : assistantMarkdown(index),
},
- );
+ ],
+ };
+ });
}
// A run would need a backend. Seeding goes through `thread.import`, which does not use this.
-const NEVER_RUNS: ChatModelAdapter = {
- run: () => {
- throw new Error("smoke-thread-weight does not run the model");
- },
-};
+const STREAM_CHUNKS = Number(
+ new URLSearchParams(window.location.search).get("stream") ?? "0",
+);
+const NEVER_RUNS: ChatModelAdapter = STREAM_CHUNKS > 0
+ ? {
+ async *run({ abortSignal }) {
+ let text = "";
+ for (let chunk = 0; chunk < STREAM_CHUNKS; chunk++) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ if (abortSignal.aborted) return;
+ text += `word${chunk} `;
+ yield { content: [{ type: "text" as const, text }] };
+ }
+ },
+ }
+ : {
+ run: () => {
+ throw new Error("smoke-thread-weight does not run the model");
+ },
+ };
function ThreadWeightApi({
setThreadMounted,
@@ -162,6 +239,15 @@ function ThreadWeightApi({
useEffect(() => {
const api = {
+ send(text: string): void {
+ aui.thread().append({
+ role: "user",
+ content: [{ type: "text", text }],
+ });
+ },
+ isRunning(): boolean {
+ return aui.thread().getState().isRunning;
+ },
/** Replace the thread with `count` messages, oldest first. */
seed(count: number, options?: SeedOptions): void {
aui
@@ -300,8 +386,54 @@ function ThreadWeightApi({
return null;
}
-function Harness(): ReactElement {
+// `?remote=1`: the remote thread list + attachments adapter the app uses, for the same scopes.
+const REMOTE = new URLSearchParams(window.location.search).get("remote") === "1";
+
+const MEMORY_THREAD_LIST: unstable_RemoteThreadListAdapter = {
+ list: async () => ({ threads: [] }),
+ rename: async () => {},
+ archive: async () => {},
+ unarchive: async () => {},
+ delete: async () => {},
+ initialize: async (threadId) => ({ remoteId: threadId, externalId: undefined }),
+ generateTitle: async () =>
+ new ReadableStream({ start: (controller) => controller.close() }) as never,
+ fetch: async (threadId) => ({
+ status: "regular",
+ remoteId: threadId,
+ externalId: undefined,
+ title: undefined,
+ }),
+};
+
+const ATTACHMENTS = new SimpleImageAttachmentAdapter();
+
+function useSmokeLocalRuntime() {
+ return useLocalRuntime(NEVER_RUNS, { adapters: { attachments: ATTACHMENTS } });
+}
+
+function RemoteHarness(): ReactElement {
+ const runtime = unstable_useRemoteThreadListRuntime({
+ runtimeHook: useSmokeLocalRuntime,
+ adapter: MEMORY_THREAD_LIST,
+ });
+ return <HarnessBody runtime={runtime} />;
+}
+
+function LocalHarness(): ReactElement {
const runtime = useLocalRuntime(NEVER_RUNS);
+ return <HarnessBody runtime={runtime} />;
+}
+
+function Harness(): ReactElement {
+ return REMOTE ? <RemoteHarness /> : <LocalHarness />;
+}
+
+function HarnessBody({
+ runtime,
+}: {
+ runtime: ReturnType<typeof useLocalRuntime>;
+}): ReactElement {
const [threadMounted, setThreadMounted] = useState(true);
return (
<TooltipProvider>
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 9a657bef0eb..89f3e507169 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -15,7 +15,6 @@ import {
getCodeFence,
isFullHtmlDocument,
isHtmlFence,
- isRenderableRenderHtmlToolPart,
isSvgFence,
} from "@/features/chat/artifacts/html-fences";
// Leaf module, not the feature barrel: SEARCH_IMAGE_TAG is read at module scope
@@ -25,11 +24,15 @@ import {
holdBackPartialSearchImageToken,
parseSearchImagesSignature,
placeSubjectImages,
- precedingTextForMessagePart,
rewriteSearchImageTokens,
SEARCH_IMAGE_TAG,
- searchImagesSignature,
} from "@/features/chat/search-images/search-images";
+import {
+ partsHaveRenderableRenderHtmlTool,
+ partsPrecedingText,
+ partsSearchImagesSignature,
+ partsTextKey,
+} from "@/components/assistant-ui/message-derived";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { normalizeEscapedInlineMath } from "@/lib/escaped-inline-math";
import { preprocessLaTeX } from "@/lib/latex";
@@ -1296,26 +1299,18 @@ const MarkdownTextImpl = () => {
const messageId = useAuiState(({ message }) => message.id);
// Read once here for every block below: see RenderHtmlToolPresenceContext.
const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>
- message.parts.some(isRenderableRenderHtmlToolPart),
+ partsHaveRenderableRenderHtmlTool(message.parts),
);
// A string, not the Map: selector results are compared by identity.
const searchImagesKey = useAuiState(({ message }) =>
- allowSearchImages ? searchImagesSignature(message.parts) : "",
+ allowSearchImages ? partsSearchImagesSignature(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)
- : "",
+ allowSearchImages ? partsPrecedingText(message.parts, partIndex) : "",
);
const messageTextKey = useAuiState(({ message }) =>
- allowSearchImages
- ? JSON.stringify(
- message.parts
- .filter((part) => part.type === "text")
- .map((part) => part.text),
- )
- : "[]",
+ allowSearchImages ? partsTextKey(message.parts) : "[]",
);
return (
diff --git a/studio/frontend/src/components/assistant-ui/message-derived.ts b/studio/frontend/src/components/assistant-ui/message-derived.ts
new file mode 100644
index 00000000000..ed4cbe4360f
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/message-derived.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Computed once per revision (#12552): assistant-ui rebuilds `parts` / `content` / `messages` on
+// any change and keeps the same array otherwise, so the array identity is the revision key.
+
+import { isRenderableRenderHtmlToolPart } from "../../features/chat/artifacts/html-fences.ts";
+import { searchImagesSignature } from "../../features/chat/search-images/search-images.ts";
+import {
+ type ContextTruncation,
+ compactionBoundary,
+ shouldShowCompactionNotice,
+} from "../../features/chat/utils/context-truncation.ts";
+
+export function memoOnArray<A extends readonly unknown[], T>(
+ compute: (array: A) => T,
+): (array: A) => T {
+ const cache = new WeakMap<A, T>();
+ return (array) => {
+ if (cache.has(array)) return cache.get(array) as T;
+ const value = compute(array);
+ cache.set(array, value);
+ return value;
+ };
+}
+
+type PartLike = { readonly type: string; readonly text?: unknown };
+
+export const partsHaveRenderableRenderHtmlTool = memoOnArray(
+ (parts: readonly unknown[]) => parts.some(isRenderableRenderHtmlToolPart),
+);
+
+export const partsTextKey = memoOnArray((parts: readonly PartLike[]) =>
+ JSON.stringify(
+ parts.filter((part) => part.type === "text").map((part) => part.text),
+ ),
+);
+
+export const partsHaveNonEmptyText = memoOnArray((parts: readonly PartLike[]) =>
+ parts.some(
+ (part) =>
+ part.type === "text" &&
+ "text" in part &&
+ (part as { text: string }).text.length > 0,
+ ),
+);
+
+export const partsSearchImagesSignature = memoOnArray(
+ (
+ parts: ReadonlyArray<{ type: string; toolName?: string; result?: unknown }>,
+ ) => searchImagesSignature(parts),
+);
+
+// Slices of one joined string (as answerTextFromParts joins); a string per part was quadratic.
+const precedingTextLayout = memoOnArray(
+ (parts: ReadonlyArray<{ type: string; text?: unknown }>) => {
+ const texts: string[] = [];
+ const ends: number[] = [];
+ let end = 0;
+ for (const part of parts) {
+ ends.push(end);
+ if (part.type === "text" && typeof part.text === "string") {
+ end += (texts.length > 0 ? 2 : 0) + part.text.length;
+ texts.push(part.text);
+ }
+ }
+ ends.push(end);
+ const joined = texts.join("\n\n");
+ return { joined, ends, slices: new Map<number, string>() };
+ },
+);
+
+export function partsPrecedingText(
+ parts: ReadonlyArray<{ type: string; text?: unknown }>,
+ partIndex: number,
+): string {
+ const layout = precedingTextLayout(parts);
+ const index = Math.max(0, Math.min(partIndex, parts.length));
+ let text = layout.slices.get(index);
+ if (text === undefined) {
+ text = layout.joined.slice(0, layout.ends[index]);
+ layout.slices.set(index, text);
+ }
+ return text;
+}
+
+type MessageLike = {
+ readonly id: string;
+ readonly role: string;
+ readonly metadata?: unknown;
+};
+
+export const compactionNoticeMessageIds = memoOnArray(
+ (messages: readonly MessageLike[]): ReadonlySet<string> => {
+ const ids = new Set<string>();
+ let previousDropped = 0;
+ for (const message of messages) {
+ if (message.role !== "assistant") continue;
+ const value = (
+ message.metadata as
+ | { custom?: { contextTruncation?: unknown } }
+ | undefined
+ )?.custom?.contextTruncation as ContextTruncation | undefined;
+ if (shouldShowCompactionNotice(value, previousDropped)) {
+ ids.add(message.id);
+ previousDropped = Math.max(previousDropped, compactionBoundary(value));
+ }
+ }
+ return ids;
+ },
+);
diff --git a/studio/frontend/src/components/assistant-ui/message-html-artifacts.tsx b/studio/frontend/src/components/assistant-ui/message-html-artifacts.tsx
index 8469b7c6ef9..e5442aa4d6e 100644
--- a/studio/frontend/src/components/assistant-ui/message-html-artifacts.tsx
+++ b/studio/frontend/src/components/assistant-ui/message-html-artifacts.tsx
@@ -8,11 +8,12 @@
// other paths to avoid duplicates: skips the message when a render_html tool
// already rendered it, and skips full documents the in-place collapse handles.
-import { ArtifactCard, useChatRuntimeStore } from "@/features/chat";
import {
- extractHtmlFences,
- isRenderableRenderHtmlToolPart,
-} from "@/features/chat/artifacts/html-fences";
+ memoOnArray,
+ partsHaveRenderableRenderHtmlTool,
+} from "@/components/assistant-ui/message-derived";
+import { ArtifactCard, useChatRuntimeStore } from "@/features/chat";
+import { extractHtmlFences } from "@/features/chat/artifacts/html-fences";
import { useAuiState } from "@assistant-ui/react";
import { type FC, useMemo } from "react";
@@ -20,21 +21,26 @@ import { type FC, useMemo } from "react";
// fence is never stitched across a non-text part (tool call, source, reasoning).
const PART_SEPARATOR = "\u0000";
+const visibleTextBlob = memoOnArray(
+ (content: ReadonlyArray<{ type: string; text?: unknown }>) =>
+ content
+ .filter((part) => part.type === "text" && "text" in part)
+ .map((part) => (part as { text: string }).text)
+ .join(PART_SEPARATOR),
+);
+
export const MessageHtmlArtifacts: FC = () => {
// Skip while streaming; "!== running" also covers loaded historical messages.
const isRunning = useAuiState(
({ message }) => message.status?.type === "running",
);
const hasRenderHtmlTool = useAuiState(({ message }) =>
- message.parts.some(isRenderableRenderHtmlToolPart),
+ partsHaveRenderableRenderHtmlTool(message.parts),
);
// Visible assistant text parts only (no reasoning, tools, sources, or errors),
// kept separate so a fence stays within the part the user actually sees.
const textBlob = useAuiState(({ message }) =>
- message.content
- .filter((part) => part.type === "text" && "text" in part)
- .map((part) => (part as { text: string }).text)
- .join(PART_SEPARATOR),
+ visibleTextBlob(message.content),
);
const collapseHtmlArtifacts = useChatRuntimeStore(
(state) => state.collapseHtmlArtifacts,
diff --git a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
index a43449ff2dd..567ac2c1940 100644
--- a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
+++ b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
@@ -15,6 +15,7 @@
// per commit, so every delete would re-render every body, action bar and tooltip: the regression #9042 removed.
import {
+ AuiProvider,
MessageByIndexProvider,
useAui,
useAuiState,
@@ -33,6 +34,7 @@ import {
useState,
} from "react";
+import { createRowNotificationGate } from "@/components/assistant-ui/row-notification-gate";
import {
type AnchorSample,
type MountWindow,
@@ -531,6 +533,8 @@ export const ProgressiveMessages: FC<{
({ renderMessage, resetKey, viewportRef }) => {
const count = useAuiState(({ thread }) => thread.messages.length);
const mountWindow = useProgressiveMountWindow(count, resetKey, viewportRef);
+ const aui = useAui();
+ const gate = useMemo(() => createRowNotificationGate(aui), [aui]);
return useMemo(() => {
if (count === 0) return null;
@@ -548,13 +552,13 @@ export const ProgressiveMessages: FC<{
const rows: ReactElement[] = [];
for (let index = first; index < count; index += 1) {
rows.push(
- <MessageByIndexProvider key={index} index={index}>
- {message}
- </MessageByIndexProvider>,
+ <AuiProvider key={index} value={gate.row(index)}>
+ <MessageByIndexProvider index={index}>{message}</MessageByIndexProvider>
+ </AuiProvider>,
);
}
return <>{rows}</>;
- }, [count, mountWindow, renderMessage]);
+ }, [count, mountWindow, renderMessage, gate]);
},
(prev, next) =>
prev.resetKey === next.resetKey &&
diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsx
index 5018532c2b8..db0bcd31879 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx
+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx
@@ -30,7 +30,6 @@ import {
import {
clearReasoningRound,
foldIsActive,
- isRenderableRenderHtmlToolPart,
resolveReasoningGroupDuration,
resolveReasoningOpen,
setReasoningRoundOpen,
@@ -58,6 +57,7 @@ import { cn } from "@/lib/utils";
import {
type ReasoningGroupComponent,
type ReasoningMessagePartComponent,
+ useAui,
useAuiState,
} from "@assistant-ui/react";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
@@ -79,7 +79,9 @@ import {
useRef,
useState,
} from "react";
-import { useShallow } from "zustand/react/shallow";
+import { shallow } from "zustand/shallow";
+import { partsHaveRenderableRenderHtmlTool } from "@/components/assistant-ui/message-derived";
+import { useMessageMemo } from "@/components/assistant-ui/use-message-memo";
const ANIMATION_DURATION = 200;
function selectionIntersectsElement(
@@ -367,21 +369,23 @@ function ReasoningCopyButton({
const [copied, setCopied] = useState(false);
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const reasoningText = useAuiState(({ message }) => {
- return message.parts
- .slice(startIndex, endIndex + 1)
+ const aui = useAui();
+
+ // Read on click: as a selector it joined all the reasoning on every store write.
+ const handleCopy = useCallback(async () => {
+ const reasoningText = aui
+ .message()
+ .getState()
+ .parts.slice(startIndex, endIndex + 1)
.filter((p) => p.type === "reasoning")
.map((p) => ("text" in p ? (p as { text: string }).text : ""))
.join("\n");
- });
-
- const handleCopy = useCallback(async () => {
if (await copyToClipboard(reasoningText)) {
setCopied(true);
if (resetRef.current) clearTimeout(resetRef.current);
resetRef.current = setTimeout(() => setCopied(false), COPY_RESET_MS);
}
- }, [reasoningText]);
+ }, [aui, startIndex, endIndex]);
return (
<IconActionButton
@@ -519,10 +523,11 @@ const ReasoningGroupImpl: ReasoningGroupComponent = (props) => {
const foldToolActivity = useChatPreferencesStore((state) =>
foldIsActive(state.foldToolActivityIntoThinking, state.toolVisibility),
);
- const folded = useAuiState(
- ({ message }) =>
+ const folded = useMessageMemo(
+ (message) =>
foldToolActivity &&
isFoldedReasoningGroup(message.parts, props.startIndex),
+ [foldToolActivity, props.startIndex],
);
if (folded) {
return <FoldedReasoningRound {...props} />;
@@ -550,10 +555,13 @@ const FoldedReasoningRound: ReasoningGroupComponent = ({
endIndex,
}) => {
const messageId = useAuiState(({ message }) => message.id);
- const roundKey = useAuiState(({ message }) => {
- const lead = leadReasoningEnd(message.parts, startIndex);
- return lead === null ? null : reasoningRoundKey(message.id, lead);
- });
+ const roundKey = useMessageMemo(
+ (message) => {
+ const lead = leadReasoningEnd(message.parts, startIndex);
+ return lead === null ? null : reasoningRoundKey(message.id, lead);
+ },
+ [startIndex],
+ );
const open = useReasoningRoundStore(
(state) => roundKey !== null && (state.open[roundKey] ?? false),
);
@@ -567,24 +575,26 @@ const FoldedReasoningRound: ReasoningGroupComponent = ({
return true;
});
const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>
- message.parts.some(isRenderableRenderHtmlToolPart),
+ partsHaveRenderableRenderHtmlTool(message.parts),
);
const reasoningContentRef = useRef<HTMLDivElement>(null);
- const reasoningDocuments = useAuiState(
- useShallow(({ message }) =>
+ const reasoningDocuments = useMessageMemo(
+ (message) =>
message.parts
.slice(startIndex, endIndex + 1)
.filter((part) => part.type === "reasoning")
.map((part) => ("text" in part ? (part as { text: string }).text : "")),
- ),
+ [startIndex, endIndex],
+ shallow,
);
const transcript = useReasoningTranscriptMode({
messageId,
reasoningDocuments,
reasoningContentRef,
});
- const closesTrace = useAuiState(({ message }) =>
- endsFoldedSpan(message.parts, endIndex),
+ const closesTrace = useMessageMemo(
+ (message) => endsFoldedSpan(message.parts, endIndex),
+ [endIndex],
);
// Hidden, not unmounted, so the text keeps streaming in while the lead is closed.
return (
@@ -614,9 +624,10 @@ const ReasoningGroupBlock = ({
foldTurn,
}: ComponentProps<ReasoningGroupComponent> & { foldTurn: boolean }) => {
// The lead of a folded span: its first Thinking block.
- const foldLead = useAuiState(
- ({ message }) =>
+ const foldLead = useMessageMemo(
+ (message) =>
foldTurn && leadReasoningEnd(message.parts, endIndex) === endIndex,
+ [foldTurn, endIndex],
);
const isReasoningStreaming = useAuiState(({ message }) => {
if (message.status?.type !== "running") {
@@ -654,18 +665,19 @@ const ReasoningGroupBlock = ({
const messageId = useAuiState(({ message }) => message.id);
const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>
- message.parts.some(isRenderableRenderHtmlToolPart),
+ partsHaveRenderableRenderHtmlTool(message.parts),
);
const reasoningContentRef = useRef<HTMLDivElement>(null);
- const reasoningDocuments = useAuiState(
- useShallow(({ message }) =>
+ const reasoningDocuments = useMessageMemo(
+ (message) =>
message.parts
.slice(startIndex, endIndex + 1)
.filter((part) => part.type === "reasoning")
.map((part) => ("text" in part ? (part as { text: string }).text : "")),
- ),
+ [startIndex, endIndex],
+ shallow,
);
const transcript = useReasoningTranscriptMode({
messageId,
@@ -673,17 +685,20 @@ const ReasoningGroupBlock = ({
reasoningContentRef,
});
- const persistedDuration = useAuiState(({ message }) => {
- const custom = message.metadata?.custom as
- | Record<string, unknown>
- | undefined;
- if (foldLead) {
- return foldedTurnDuration(message.parts, endIndex, (parts, start) =>
- resolveReasoningGroupDuration(parts, start, custom),
- );
- }
- return resolveReasoningGroupDuration(message.parts, startIndex, custom);
- });
+ const persistedDuration = useMessageMemo(
+ (message) => {
+ const custom = message.metadata?.custom as
+ | Record<string, unknown>
+ | undefined;
+ if (foldLead) {
+ return foldedTurnDuration(message.parts, endIndex, (parts, start) =>
+ resolveReasoningGroupDuration(parts, start, custom),
+ );
+ }
+ return resolveReasoningGroupDuration(message.parts, startIndex, custom);
+ },
+ [foldLead, startIndex, endIndex],
+ );
const visibility = useChatPreferencesStore(
(state) => state.thinkingVisibility,
@@ -734,22 +749,27 @@ const ReasoningGroupBlock = ({
// its header. A layout effect, so the folded parts settle before the frame the user sees.
const roundKey = reasoningRoundKey(messageId, endIndex);
const toolConfirmations = useChatRuntimeStore((s) => s.toolConfirmations);
- const foldedToolCount = useAuiState(({ message }) =>
- foldLead
- ? countFoldedToolParts(message.parts, endIndex, (start, end) =>
- toolRunIsExempt(message.parts, start, end, toolConfirmations),
- )
- : 0,
+ const foldedToolCount = useMessageMemo(
+ (message) =>
+ foldLead
+ ? countFoldedToolParts(message.parts, endIndex, (start, end) =>
+ toolRunIsExempt(message.parts, start, end, toolConfirmations),
+ )
+ : 0,
+ [foldLead, endIndex, toolConfirmations],
);
// Copy reaches the rounds folded in here too: they have no Copy of their own.
- const copyEndIndex = useAuiState(({ message }) =>
- foldLead ? foldEnd(message.parts, endIndex) - 1 : endIndex,
+ const copyEndIndex = useMessageMemo(
+ (message) => (foldLead ? foldEnd(message.parts, endIndex) - 1 : endIndex),
+ [foldLead, endIndex],
);
// The answer follows this block directly, with nothing folded in between.
- const closesTrace = useAuiState(({ message }) =>
- foldLead
- ? endsFoldedSpan(message.parts, endIndex)
- : message.parts[endIndex + 1]?.type === "text",
+ const closesTrace = useMessageMemo(
+ (message) =>
+ foldLead
+ ? endsFoldedSpan(message.parts, endIndex)
+ : message.parts[endIndex + 1]?.type === "text",
+ [foldLead, endIndex],
);
useLayoutEffect(() => {
if (!foldLead) return;
diff --git a/studio/frontend/src/components/assistant-ui/row-notification-gate.ts b/studio/frontend/src/components/assistant-ui/row-notification-gate.ts
new file mode 100644
index 00000000000..c6784516ffa
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/row-notification-gate.ts
@@ -0,0 +1,259 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Every store write re-runs every row's selectors (#12552), so rows subscribe through a gate: a
+// keystroke reaches no row; a same-length `thread.messages` change reaches rows from one before
+// the first changed one (rows read their own, earlier or the next message); else every row.
+// Assumes scope methods change only with `thread.messages` (assistant-ui 0.12): recheck on upgrade.
+
+import type { AssistantClient } from "@assistant-ui/react";
+
+type Listener = () => void;
+
+export interface RowFingerprint {
+ rest: unknown[];
+ messages: readonly unknown[] | null;
+ repository: unknown;
+}
+
+const TYPED_COMPOSER_FIELDS = new Set(["text", "isEmpty"]);
+const EMPTY: readonly unknown[] = [];
+const ROW_MESSAGES = Symbol("row messages");
+const UNKNOWN_REPOSITORY = Symbol("unknown repository");
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+function isThreadState(value: Record<string, unknown>): boolean {
+ return "messages" in value && "composer" in value;
+}
+
+function isThreadListState(value: Record<string, unknown>): boolean {
+ return "main" in value && "threadItems" in value;
+}
+
+function isComposerState(value: Record<string, unknown>): boolean {
+ return "text" in value && "isEmpty" in value && "attachments" in value;
+}
+
+function pushComposer(out: unknown[], composer: unknown): void {
+ if (!isRecord(composer)) {
+ out.push(composer);
+ return;
+ }
+ for (const key of Object.keys(composer)) {
+ if (TYPED_COMPOSER_FIELDS.has(key)) continue;
+ const value = composer[key];
+ // The composer state is rebuilt per keystroke with a fresh `queue: []` literal.
+ out.push(Array.isArray(value) && value.length === 0 ? EMPTY : value);
+ }
+}
+
+// These states embed the composer, so compare their fields, not the container.
+function pushState(
+ out: unknown[],
+ state: unknown,
+ rowMessages: readonly unknown[] | null,
+): void {
+ if (!isRecord(state)) {
+ out.push(state);
+ return;
+ }
+ if (isThreadState(state)) {
+ for (const key of Object.keys(state)) {
+ const value = state[key];
+ if (key === "composer") pushComposer(out, value);
+ else if (key === "messages" && value === rowMessages)
+ out.push(ROW_MESSAGES);
+ else out.push(value);
+ }
+ return;
+ }
+ if (isThreadListState(state)) {
+ for (const key of Object.keys(state)) {
+ if (key === "main") pushState(out, state.main, rowMessages);
+ else out.push(state[key]);
+ }
+ return;
+ }
+ if (isComposerState(state)) {
+ pushComposer(out, state);
+ return;
+ }
+ out.push(state);
+}
+
+function scopeState(client: AssistantClient, key: string): unknown {
+ const scope = (client as unknown as Record<string, unknown>)[key];
+ if (typeof scope !== "function") return undefined;
+ const methods = (scope as () => unknown)();
+ const getState = isRecord(methods) ? methods.getState : undefined;
+ if (typeof getState !== "function") return undefined;
+ return getState.call(methods);
+}
+
+// Rebuilt on every repository write, hidden branches included, but not when only the store rebuilds
+// `thread.messages` (the first keystroke after a run does).
+function repositoryRevision(client: AssistantClient): unknown {
+ const thread = (client as unknown as Record<string, unknown>).thread;
+ if (typeof thread !== "function") return UNKNOWN_REPOSITORY;
+ const methods = (thread as () => unknown)();
+ const getRuntime = isRecord(methods)
+ ? methods.__internal_getRuntime
+ : undefined;
+ if (typeof getRuntime !== "function") return UNKNOWN_REPOSITORY;
+ const runtime = getRuntime.call(methods);
+ const getState = isRecord(runtime) ? runtime.getState : undefined;
+ if (typeof getState !== "function") return UNKNOWN_REPOSITORY;
+ const state = getState.call(runtime);
+ return isRecord(state) && Array.isArray(state.messages)
+ ? state.messages
+ : UNKNOWN_REPOSITORY;
+}
+
+export function rowFingerprint(client: AssistantClient): RowFingerprint {
+ let messages: readonly unknown[] | null = null;
+ let repository: unknown = UNKNOWN_REPOSITORY;
+ try {
+ const thread = scopeState(client, "thread");
+ if (isRecord(thread) && Array.isArray(thread.messages))
+ messages = thread.messages;
+ repository = repositoryRevision(client);
+ } catch {
+ // No thread scope: every change lands in `rest` and reaches every row.
+ }
+ const rest: unknown[] = [];
+ for (const key in client) {
+ if (key === "subscribe" || key === "on") continue;
+ let state: unknown;
+ try {
+ state = scopeState(client, key);
+ } catch {
+ continue;
+ }
+ if (state === undefined) continue;
+ rest.push(key);
+ pushState(rest, state, messages);
+ }
+ return { rest, messages, repository };
+}
+
+function sameValues(a: readonly unknown[], b: readonly unknown[]): boolean {
+ if (a.length !== b.length) return false;
+ for (let index = 0; index < a.length; index += 1) {
+ if (!Object.is(a[index], b[index])) return false;
+ }
+ return true;
+}
+
+export function rowsToNotify(
+ last: RowFingerprint | null,
+ next: RowFingerprint | null,
+): "none" | "all" | number {
+ if (last === null || next === null || !sameValues(last.rest, next.rest)) {
+ return "all";
+ }
+ if (last.messages === next.messages) return "none";
+ if (
+ last.messages === null ||
+ next.messages === null ||
+ last.messages.length !== next.messages.length
+ ) {
+ return "all";
+ }
+ for (let index = 0; index < next.messages.length; index += 1) {
+ if (last.messages[index] !== next.messages[index]) {
+ return Math.max(0, index - 1);
+ }
+ }
+ // A hidden branch changed: selectors keyed on the array (research reply owners) must hear it.
+ return last.repository !== UNKNOWN_REPOSITORY &&
+ last.repository === next.repository
+ ? "none"
+ : "all";
+}
+
+export interface RowNotificationGate {
+ row(index: number): AssistantClient;
+}
+
+function withSubscribe(
+ parent: AssistantClient,
+ subscribe: (listener: Listener) => () => void,
+): AssistantClient {
+ const client = Object.create(parent) as AssistantClient;
+ Object.defineProperty(client, "subscribe", {
+ value: subscribe,
+ enumerable: false,
+ configurable: true,
+ writable: true,
+ });
+ return client;
+}
+
+export function createRowNotificationGate(
+ parent: AssistantClient,
+): RowNotificationGate {
+ const entries = new Set<{ listener: Listener; index: number }>();
+ const rows = new Map<number, AssistantClient>();
+ let release: (() => void) | null = null;
+ let last: RowFingerprint | null = null;
+
+ const fingerprint = (): RowFingerprint | null => {
+ try {
+ return rowFingerprint(parent);
+ } catch (error) {
+ console.error("row notification gate: fingerprint error", error);
+ return null;
+ }
+ };
+
+ const onParentNotify = () => {
+ const next = fingerprint();
+ const from = rowsToNotify(last, next);
+ last = next;
+ if (from === "none") return;
+ for (const entry of entries) {
+ if (from !== "all" && entry.index < from) continue;
+ try {
+ entry.listener();
+ } catch (error) {
+ console.error(
+ "row notification gate: subscriber callback error",
+ error,
+ );
+ }
+ }
+ };
+
+ const subscribe = (index: number, listener: Listener) => {
+ const entry = { listener, index };
+ entries.add(entry);
+ if (release === null) {
+ last = fingerprint();
+ release = parent.subscribe(onParentNotify);
+ }
+ return () => {
+ entries.delete(entry);
+ if (entries.size === 0 && release !== null) {
+ release();
+ release = null;
+ last = null;
+ }
+ };
+ };
+
+ return {
+ row(index: number): AssistantClient {
+ let client = rows.get(index);
+ if (client === undefined) {
+ client = withSubscribe(parent, (listener) =>
+ subscribe(index, listener),
+ );
+ rows.set(index, client);
+ }
+ return client;
+ },
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 0db6690a522..15046b93f43 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -21,11 +21,8 @@ import {
useGeneratedImageOverlay,
} from "@/components/assistant-ui/generated-image-overlay-context";
import { CompactionNotice } from "@/components/assistant-ui/compaction-notice";
-import {
- compactionBoundary,
- shouldShowCompactionNotice,
- type ContextTruncation,
-} from "@/features/chat/utils/context-truncation";
+import { compactionNoticeMessageIds } from "@/components/assistant-ui/message-derived";
+import type { ContextTruncation } from "@/features/chat/utils/context-truncation";
import { downloadImagePart } from "@/components/assistant-ui/image";
import { MarkdownText } from "@/components/assistant-ui/markdown-text";
import { MessageHtmlArtifacts } from "@/components/assistant-ui/message-html-artifacts";
@@ -7895,25 +7892,9 @@ const AssistantMessage: FC = () => {
// matters is when MORE of the conversation fell out of view: the eviction boundary
// rising above the last turn that reported one, or a checkpoint starting inside a tool
// loop (which evicts without moving the boundary). Sticky replays stay quiet.
- const showsNotice = useAuiState(({ thread }) => {
- let previousDropped = 0;
- for (const message of thread.messages) {
- if (message.role !== "assistant") continue;
- const value = (
- message.metadata as
- | { custom?: { contextTruncation?: unknown } }
- | undefined
- )?.custom?.contextTruncation as ContextTruncation | undefined;
- const dropped = compactionBoundary(value);
- if (shouldShowCompactionNotice(value, previousDropped)) {
- if (message.id === messageId) return true;
- previousDropped = Math.max(previousDropped, dropped);
- } else if (message.id === messageId) {
- return false;
- }
- }
- return false;
- });
+ const showsNotice = useAuiState(({ thread }) =>
+ compactionNoticeMessageIds(thread.messages).has(messageId),
+ );
const incognito = useChatRuntimeStore((s) => s.incognito);
// Use global store for editing state to ensure a single source of truth
diff --git a/studio/frontend/src/components/assistant-ui/tool-group.tsx b/studio/frontend/src/components/assistant-ui/tool-group.tsx
index 7664f323f1d..fa2cd00021f 100644
--- a/studio/frontend/src/components/assistant-ui/tool-group.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-group.tsx
@@ -9,6 +9,7 @@ import {
type PropsWithChildren,
} from "react";
import { useAuiState } from "@assistant-ui/react";
+import { useMessageMemo } from "@/components/assistant-ui/use-message-memo";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
// eslint-disable-next-line no-restricted-imports -- this file is in the startup cycle; the chat barrel closes it.
@@ -266,24 +267,28 @@ const ToolGroupImpl: FC<
PropsWithChildren<{ startIndex: number; endIndex: number }>
> = ({ children, startIndex, endIndex }) => {
const toolCount = endIndex - startIndex + 1;
- const containsUngroupedTool = useAuiState(({ message }) =>
- message.parts.slice(startIndex, endIndex + 1).some(holdsOwnOutput),
+ const containsUngroupedTool = useMessageMemo(
+ (message) =>
+ message.parts.slice(startIndex, endIndex + 1).some(holdsOwnOutput),
+ [startIndex, endIndex],
);
// A blocking allow/deny prompt must never be hidden inside a collapsed
// group, so force the group open while any of its calls awaits confirmation.
const toolConfirmations = useChatRuntimeStore((s) => s.toolConfirmations);
- const hasPendingConfirmation = useAuiState(({ message }) =>
- message.parts
- .slice(startIndex, endIndex + 1)
- .some((part) => awaitsConfirmation(part, toolConfirmations)),
+ const hasPendingConfirmation = useMessageMemo(
+ (message) =>
+ message.parts
+ .slice(startIndex, endIndex + 1)
+ .some((part) => awaitsConfirmation(part, toolConfirmations)),
+ [startIndex, endIndex, toolConfirmations],
);
const messageRunning = useAuiState(
({ message }) => message.status?.type === "running",
);
// Still working: a part inherits the message status until it has a result, so the group goes
// quiet once every call in it has one, without waiting for the rest of the turn.
- const groupRunning = useAuiState(
- ({ message }) =>
+ const groupRunning = useMessageMemo(
+ (message) =>
message.status?.type === "running" &&
message.parts
.slice(startIndex, endIndex + 1)
@@ -292,6 +297,7 @@ const ToolGroupImpl: FC<
part.type === "tool-call" &&
(part as { result?: unknown }).result === undefined,
),
+ [startIndex, endIndex],
);
// Only collapsed suppresses the forced opens below. Auto and expanded want it open anyway.
const collapseByDefault = useChatPreferencesStore(
@@ -301,23 +307,25 @@ const ToolGroupImpl: FC<
const toolLiveOutput = useChatRuntimeStore((s) => s.toolLiveOutput);
const paneScope = useToolPaneScope();
const unresolvedScope = useUnresolvedToolPaneScope();
- const hasLiveOutput = useAuiState(({ message }) =>
- message.parts
- .slice(startIndex, endIndex + 1)
- .some(
- (part) =>
- part.type === "tool-call" &&
- // Either scope: a first turn writes under the unresolved one for its whole
- // life, even after the autosave assigns the id (see useToolOutputFor).
- (Object.prototype.hasOwnProperty.call(
- toolLiveOutput,
- toolOutputKey(paneScope, part.toolCallId),
- ) ||
- Object.prototype.hasOwnProperty.call(
+ const hasLiveOutput = useMessageMemo(
+ (message) =>
+ message.parts
+ .slice(startIndex, endIndex + 1)
+ .some(
+ (part) =>
+ part.type === "tool-call" &&
+ // Either scope: a first turn writes under the unresolved one for its whole
+ // life, even after the autosave assigns the id (see useToolOutputFor).
+ (Object.prototype.hasOwnProperty.call(
toolLiveOutput,
- toolOutputKey(unresolvedScope, part.toolCallId),
- )),
- ),
+ toolOutputKey(paneScope, part.toolCallId),
+ ) ||
+ Object.prototype.hasOwnProperty.call(
+ toolLiveOutput,
+ toolOutputKey(unresolvedScope, part.toolCallId),
+ )),
+ ),
+ [startIndex, endIndex, toolLiveOutput, paneScope, unresolvedScope],
);
// Keep the group open once a confirmation or live output forced it (so an
// allow/deny doesn't snap it shut between calls); reverts once the turn ends.
@@ -339,20 +347,24 @@ const ToolGroupImpl: FC<
const foldToolActivity = useChatPreferencesStore((state) =>
foldIsActive(state.foldToolActivityIntoThinking, state.toolVisibility),
);
- const roundKey = useAuiState(({ message }) => {
- const reasoningEnd = governingReasoningEnd(message.parts, startIndex);
- return reasoningEnd === null
- ? null
- : reasoningRoundKey(message.id, reasoningEnd);
- });
+ const roundKey = useMessageMemo(
+ (message) => {
+ const reasoningEnd = governingReasoningEnd(message.parts, startIndex);
+ return reasoningEnd === null
+ ? null
+ : reasoningRoundKey(message.id, reasoningEnd);
+ },
+ [startIndex],
+ );
const roundOpen = useReasoningRoundStore((state) =>
roundKey === null ? true : (state.open[roundKey] ?? false),
);
const underThinking = foldToolActivity && roundKey !== null;
const exempt = containsUngroupedTool || hasPendingConfirmation;
// Last thing under the block, with the answer right after: close the trace with a rule.
- const closesTrace = useAuiState(({ message }) =>
- endsFoldedSpan(message.parts, endIndex),
+ const closesTrace = useMessageMemo(
+ (message) => endsFoldedSpan(message.parts, endIndex),
+ [endIndex],
);
// Render single calls, canvases, Python scripts, and calls that created files
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
index a00e9d98c36..6d9f6d70788 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
@@ -9,6 +9,7 @@ import {
type ToolCallMessagePartComponent,
useAuiState,
} from "@assistant-ui/react";
+import { partsHaveNonEmptyText } from "@/components/assistant-ui/message-derived";
import { TerminalIcon } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
import { isToolCallRunning, toolArgText } from "./tool-arg-text";
@@ -134,12 +135,7 @@ const CodeExecutionToolUIImpl: ToolCallMessagePartComponent = ({
// Collapse the card once the model resumes streaming prose after the tool
// call (mirrors WebSearchToolUI) so it doesn't crowd the final answer.
const hasText = useAuiState(({ message }) =>
- message.content.some(
- (p) =>
- p.type === "text" &&
- "text" in p &&
- (p as { text: string }).text.length > 0,
- ),
+ partsHaveNonEmptyText(message.content),
);
// Ask permission gates every local tool call, and what is being approved
// lives inside the content while Allow/Deny render outside it.
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
index 1e1484184c9..28a8024e195 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
@@ -7,6 +7,7 @@ import {
type ToolCallMessagePartComponent,
useAuiState,
} from "@assistant-ui/react";
+import { partsHaveNonEmptyText } from "@/components/assistant-ui/message-derived";
import { LibraryBigIcon } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
@@ -98,12 +99,7 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({
);
const hasText = useAuiState(({ message }) =>
- message.content.some(
- (p) =>
- p.type === "text" &&
- "text" in p &&
- (p as { text: string }).text.length > 0,
- ),
+ partsHaveNonEmptyText(message.content),
);
// Ask permission gates every local tool call, and what is being approved
// lives inside the content while Allow/Deny render outside it.
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx
index 398d7468f3c..1a461188886 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-read-skill.tsx
@@ -8,6 +8,7 @@ import {
type ToolCallMessagePartComponent,
useAuiState,
} from "@assistant-ui/react";
+import { partsHaveNonEmptyText } from "@/components/assistant-ui/message-derived";
import { Scroll01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { type ComponentProps, memo } from "react";
@@ -52,12 +53,7 @@ const ReadSkillToolUIImpl: ToolCallMessagePartComponent = ({
? `Reading ${name}…`
: `Read ${name} · ${resource}`;
const hasText = useAuiState(({ message }) =>
- message.content.some(
- (part) =>
- part.type === "text" &&
- "text" in part &&
- (part as { text: string }).text.length > 0,
- ),
+ partsHaveNonEmptyText(message.content),
);
const awaitingApproval = useToolAwaitingApproval(toolCallId);
const [open, setOpen] = useToolActivityOpen(isRunning, hasText);
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
index c2a046d62cc..19a998a8d1a 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
@@ -3,6 +3,7 @@
"use client";
+import { partsHaveNonEmptyText } from "@/components/assistant-ui/message-derived";
import {
type ToolCallMessagePartComponent,
useAuiState,
@@ -153,12 +154,7 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({
// Collapse when LLM starts generating text after the tool call
const hasText = useAuiState(({ message }) =>
- message.content.some(
- (p) =>
- p.type === "text" &&
- "text" in p &&
- (p as { text: string }).text.length > 0,
- ),
+ partsHaveNonEmptyText(message.content),
);
// Ask permission gates every local tool call, and what is being approved
// lives inside the content while Allow/Deny render outside it.
diff --git a/studio/frontend/src/components/assistant-ui/use-message-memo.ts b/studio/frontend/src/components/assistant-ui/use-message-memo.ts
new file mode 100644
index 00000000000..a35a9118d8b
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/use-message-memo.ts
@@ -0,0 +1,46 @@
+// 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 { useAuiState } from "@assistant-ui/react";
+import { useRef } from "react";
+
+type MessageState = Parameters<Parameters<typeof useAuiState>[0]>[0]["message"];
+
+function sameDeps(a: readonly unknown[], b: readonly unknown[]): boolean {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i += 1) {
+ if (!Object.is(a[i], b[i])) return false;
+ }
+ return true;
+}
+
+/** `useAuiState(({ message }) => select(message))` re-run only when the message or `deps` change.
+ * `select` must read nothing else; `equal` keeps the previous result when they match. */
+export function useMessageMemo<T>(
+ select: (message: MessageState) => T,
+ deps: readonly unknown[],
+ equal?: (a: T, b: T) => boolean,
+): T {
+ const memo = useRef<{
+ message: MessageState;
+ deps: readonly unknown[];
+ value: T;
+ } | null>(null);
+ return useAuiState(({ message }) => {
+ const last = memo.current;
+ if (
+ last !== null &&
+ last.message === message &&
+ sameDeps(last.deps, deps)
+ ) {
+ return last.value;
+ }
+ const next = select(message);
+ const value =
+ last !== null && equal !== undefined && equal(last.value, next)
+ ? last.value
+ : next;
+ memo.current = { message, deps, value };
+ return value;
+ });
+}
diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.ts
index 13f53e5c10f..b143f923a78 100644
--- a/studio/frontend/tests/chat-continuation.test.ts
+++ b/studio/frontend/tests/chat-continuation.test.ts
@@ -1833,7 +1833,7 @@ test("a losing claim does not follow the row onto the next branch", () => {
const rows = readSrc("components/assistant-ui/progressive-messages.tsx");
assert.match(
rows,
- /<MessageByIndexProvider key=\{index\}/,
+ /<AuiProvider key=\{index\} value=\{gate\.row\(index\)\}>\s*<MessageByIndexProvider index=\{index\}>/,
"rows are no longer keyed by index; this test needs rewriting",
);
diff --git a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
index 893f901f518..85ba827eade 100644
--- a/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
+++ b/studio/frontend/tests/composer-keystroke-subscription-budget.test.ts
@@ -64,7 +64,7 @@ test("the render_html scan happens once per message part, above the blocks", ()
);
assert.match(
impl,
- /useAuiState\(\(\{ message \}\) =>\s*message\.parts\.some\(isRenderableRenderHtmlToolPart\),?\s*\)/,
+ /useAuiState\(\(\{ message \}\) =>\s*partsHaveRenderableRenderHtmlTool\(message\.parts\),?\s*\)/,
);
// The value has to reach the blocks, or the context read above answers with its default.
assert.match(
diff --git a/studio/frontend/tests/message-derived.test.ts b/studio/frontend/tests/message-derived.test.ts
new file mode 100644
index 00000000000..e816a35811c
--- /dev/null
+++ b/studio/frontend/tests/message-derived.test.ts
@@ -0,0 +1,193 @@
+// 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 {
+ compactionNoticeMessageIds,
+ memoOnArray,
+ partsHaveNonEmptyText,
+ partsHaveRenderableRenderHtmlTool,
+ partsPrecedingText,
+ partsSearchImagesSignature,
+ partsTextKey,
+} from "../src/components/assistant-ui/message-derived.ts";
+import {
+ shouldShowCompactionNotice,
+ compactionBoundary,
+} from "../src/features/chat/utils/context-truncation.ts";
+import {
+ precedingTextForMessagePart,
+ searchImagesSignature,
+} from "../src/features/chat/search-images/search-images.ts";
+
+test("memoOnArray computes once per array and again for a new array", () => {
+ let calls = 0;
+ const length = memoOnArray((a: readonly number[]) => {
+ calls += 1;
+ return a.length;
+ });
+ const a = [1, 2, 3];
+ assert.equal(length(a), 3);
+ assert.equal(length(a), 3);
+ assert.equal(calls, 1);
+ assert.equal(length([...a, 4]), 4);
+ assert.equal(calls, 2);
+});
+
+const parts = [
+ { type: "reasoning", text: "thinking" },
+ { type: "text", text: "first answer" },
+ {
+ type: "tool-call",
+ toolName: "render_html",
+ toolCallId: "c1",
+ args: { code: "<p>x</p>" },
+ result: "Rendered HTML canvas",
+ },
+ { type: "text", text: "" },
+ { type: "text", text: "second answer" },
+];
+
+test("cached part values equal the uncached computations", () => {
+ assert.equal(
+ partsTextKey(parts),
+ JSON.stringify(["first answer", "", "second answer"]),
+ );
+ assert.equal(partsHaveRenderableRenderHtmlTool(parts), true);
+ assert.equal(partsHaveRenderableRenderHtmlTool(parts.slice(0, 2)), false);
+ assert.equal(partsHaveNonEmptyText(parts), true);
+ assert.equal(partsHaveNonEmptyText([{ type: "text", text: "" }]), false);
+ assert.equal(partsSearchImagesSignature(parts), searchImagesSignature(parts));
+ for (let i = 0; i < parts.length; i += 1) {
+ assert.equal(
+ partsPrecedingText(parts, i),
+ precedingTextForMessagePart(parts, i),
+ );
+ }
+});
+
+test("preceding text matches the uncached join on random part mixes, and is one string per index", () => {
+ let seed = 7;
+ const random = () => {
+ seed = (seed * 1103515245 + 12345) % 2147483648;
+ return seed / 2147483648;
+ };
+ const kinds = ["text", "reasoning", "tool-call", "text"];
+ for (let round = 0; round < 300; round += 1) {
+ const mix = Array.from({ length: Math.floor(random() * 12) }, (_, i) => {
+ const type = kinds[Math.floor(random() * kinds.length)];
+ return random() < 0.1
+ ? { type }
+ : { type, text: random() < 0.2 ? "" : `${type} ${round} ${i}` };
+ });
+ for (let i = 0; i <= mix.length + 1; i += 1) {
+ assert.equal(
+ partsPrecedingText(mix, i),
+ precedingTextForMessagePart(mix, i),
+ );
+ assert.equal(partsPrecedingText(mix, i), partsPrecedingText(mix, i));
+ }
+ }
+});
+
+test("an appended part is a new array and is not served the old answer", () => {
+ const streamed = [{ type: "text", text: "a" }];
+ assert.equal(partsTextKey(streamed), '["a"]');
+ const next = [{ type: "text", text: "ab" }];
+ assert.equal(partsTextKey(next), '["ab"]');
+ assert.equal(partsPrecedingText(next, 1), "ab");
+});
+
+// The walk AssistantMessage did per message before #12552, kept here as the oracle.
+function walk(
+ messages: readonly { id: string; role: string; metadata?: unknown }[],
+ messageId: string,
+): boolean {
+ let previousDropped = 0;
+ for (const message of messages) {
+ if (message.role !== "assistant") continue;
+ const value = (
+ message.metadata as
+ | { custom?: { contextTruncation?: unknown } }
+ | undefined
+ )?.custom?.contextTruncation as Parameters<typeof compactionBoundary>[0];
+ const dropped = compactionBoundary(value);
+ if (shouldShowCompactionNotice(value, previousDropped)) {
+ if (message.id === messageId) return true;
+ previousDropped = Math.max(previousDropped, dropped);
+ } else if (message.id === messageId) {
+ return false;
+ }
+ }
+ return false;
+}
+
+test("compaction notice ids match the per-message walk", () => {
+ const truncation = (custom: Record<string, unknown>) => ({
+ custom: { contextTruncation: custom },
+ });
+ const messages = [
+ { id: "u0", role: "user" },
+ { id: "a0", role: "assistant" },
+ {
+ id: "a1",
+ role: "assistant",
+ metadata: truncation({
+ dropped_messages: 4,
+ boundary_messages: 4,
+ fits: true,
+ }),
+ },
+ {
+ id: "a2",
+ role: "assistant",
+ metadata: truncation({
+ dropped_messages: 4,
+ boundary_messages: 4,
+ fits: true,
+ }),
+ },
+ {
+ id: "a3",
+ role: "assistant",
+ metadata: truncation({
+ dropped_messages: 2,
+ boundary_messages: 3,
+ checkpoint_started: true,
+ }),
+ },
+ {
+ id: "a4",
+ role: "assistant",
+ metadata: truncation({
+ dropped_messages: 8,
+ boundary_messages: 9,
+ fits: true,
+ }),
+ },
+ {
+ id: "a5",
+ role: "assistant",
+ metadata: truncation({ dropped_messages: 0 }),
+ },
+ {
+ id: "a6",
+ role: "assistant",
+ metadata: truncation({ dropped_messages: 5, fits: false }),
+ },
+ {
+ id: "u1",
+ role: "user",
+ metadata: truncation({ dropped_messages: 50, boundary_messages: 50 }),
+ },
+ ];
+ const ids = compactionNoticeMessageIds(messages);
+ for (const message of messages) {
+ assert.equal(ids.has(message.id), walk(messages, message.id), message.id);
+ }
+ assert.deepEqual([...ids], ["a1", "a3", "a4"]);
+ assert.equal(ids.has("missing"), false);
+ assert.equal(compactionNoticeMessageIds(messages), ids);
+ assert.notEqual(compactionNoticeMessageIds([...messages]), ids);
+});
diff --git a/studio/frontend/tests/progressive-mount-glue.test.ts b/studio/frontend/tests/progressive-mount-glue.test.ts
index e7b40219d43..7cb0f3a8895 100644
--- a/studio/frontend/tests/progressive-mount-glue.test.ts
+++ b/studio/frontend/tests/progressive-mount-glue.test.ts
@@ -56,7 +56,10 @@ test("the thread renders rows through MessageByIndex, never ThreadPrimitive.Mess
// Upstream renders MessageByIndexProvider -> RenderChildrenWithAccessor -> children; this row map
// renders MessageByIndexProvider -> children. Switching between the two on convergence would
// change the element type at that position, so React would unmount and rebuild every message.
- assert.match(GLUE, /<MessageByIndexProvider key=\{index\} index=\{index\}>/);
+ assert.match(
+ GLUE,
+ /<AuiProvider key=\{index\} value=\{gate\.row\(index\)\}>\s*<MessageByIndexProvider index=\{index\}>/,
+ );
assert.doesNotMatch(
GLUE,
/<ThreadPrimitive\.Messages\b/,
@@ -309,7 +312,11 @@ test("the row map is memoized on the slot identity", () => {
// identity; rebuilding 220 elements per Thread re-render hands back what the windowing collects.
assert.match(
GLUE,
- /useMemo\(\(\) => \{[\s\S]*?\}, \[count, mountWindow, renderMessage\]\)/,
+ /useMemo\(\(\) => \{[\s\S]*?\}, \[count, mountWindow, renderMessage, gate\]\)/,
+ );
+ assert.match(
+ GLUE,
+ /const gate = useMemo\(\(\) => createRowNotificationGate\(aui\), \[aui\]\)/,
);
assert.match(GLUE, /prev\.renderMessage === next\.renderMessage/);
assert.match(THREAD, /const renderThreadMessage = proplessSlot\(/);
diff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.ts
index c948cf1b8fd..2eb8b2d3c33 100644
--- a/studio/frontend/tests/rolling-context-window.test.ts
+++ b/studio/frontend/tests/rolling-context-window.test.ts
@@ -15,6 +15,7 @@ import { readSrc } from "./helpers/kit.ts";
const COMPACTION_NOTICE = readSrc("components/assistant-ui/compaction-notice.tsx");
const THREAD = readSrc("components/assistant-ui/thread.tsx");
+const DERIVED = readSrc("components/assistant-ui/message-derived.ts");
const CHAT_ADAPTER = readSrc("features/chat/api/chat-adapter.ts");
const adapter = readSrc("features/chat/api/chat-adapter.ts");
@@ -222,10 +223,11 @@ test("the compaction notice uses the shared boundary/checkpoint predicate", () =
// Replayed fits stay quiet; a new boundary or checkpoint is a new compaction.
assert.match(THREAD, /const showsNotice = useAuiState/);
assert.match(THREAD, /contextTruncation && showsNotice && !isEditing/);
- assert.match(THREAD, /shouldShowCompactionNotice\(value, previousDropped\)/);
+ assert.match(THREAD, /compactionNoticeMessageIds\(thread\.messages\)\.has\(messageId\)/);
+ assert.match(DERIVED, /shouldShowCompactionNotice\(value, previousDropped\)/);
// Walked in order, not against the preceding message: turns between two moves report
// the same count and must not reset the baseline.
- assert.match(THREAD, /for \(const message of thread\.messages\)/);
+ assert.match(DERIVED, /for \(const message of messages\)/);
});
// The gate is a pure function of the thread's persisted truncation counts, so it can be
diff --git a/studio/frontend/tests/row-notification-gate.test.ts b/studio/frontend/tests/row-notification-gate.test.ts
new file mode 100644
index 00000000000..2edc2c42b55
--- /dev/null
+++ b/studio/frontend/tests/row-notification-gate.test.ts
@@ -0,0 +1,274 @@
+// 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 type { AssistantClient } from "@assistant-ui/react";
+import { createRowNotificationGate } from "../src/components/assistant-ui/row-notification-gate.ts";
+
+type State = Record<string, unknown>;
+
+// Enumerable scopes with `getState`, one channel, the composer inside thread state.
+function fakeClient() {
+ const messages: unknown[] = [
+ { id: "m0" },
+ { id: "m1" },
+ { id: "m2" },
+ { id: "m3" },
+ ];
+ let composer: State = {
+ text: "",
+ isEmpty: true,
+ attachments: [],
+ dictation: undefined,
+ queue: [],
+ };
+ let thread: State = { isRunning: false, messages, composer };
+ let threads: State = { mainThreadId: "t1", threadItems: {}, main: thread };
+ let tools: State = { tools: {} };
+ let repository: unknown[] = [];
+ const listeners = new Set<() => void>();
+ let parentSubscriptions = 0;
+ const client = {
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ parentSubscriptions += 1;
+ return () => {
+ listeners.delete(listener);
+ parentSubscriptions -= 1;
+ };
+ },
+ on() {
+ return () => {};
+ },
+ threads: () => ({ getState: () => threads }),
+ thread: () => ({
+ getState: () => thread,
+ __internal_getRuntime: () => ({
+ getState: () => ({ messages: repository }),
+ }),
+ }),
+ composer: () => ({ getState: () => composer }),
+ tools: () => ({ getState: () => tools }),
+ };
+ const publish = (next: {
+ composer?: State;
+ thread?: State;
+ tools?: State;
+ repositoryWrite?: boolean;
+ }) => {
+ if (next.repositoryWrite) repository = [...repository];
+ if (next.composer) composer = next.composer;
+ thread = { ...thread, ...(next.thread ?? {}), composer };
+ threads = { ...threads, main: thread };
+ if (next.tools) tools = next.tools;
+ for (const listener of listeners) listener();
+ };
+ return {
+ client: client as unknown as AssistantClient,
+ publish,
+ composer: () => composer,
+ thread: () => thread,
+ parentSubscriptions: () => parentSubscriptions,
+ };
+}
+
+function subscribeRows(fake: ReturnType<typeof fakeClient>, count: number) {
+ const gate = createRowNotificationGate(fake.client);
+ const heard = Array.from({ length: count }, () => 0);
+ const release = heard.map((_, index) =>
+ gate.row(index).subscribe(() => {
+ heard[index] += 1;
+ }),
+ );
+ return {
+ gate,
+ heard,
+ release: () => {
+ for (const r of release) r();
+ },
+ };
+}
+
+function withMessage(fake: ReturnType<typeof fakeClient>, index: number) {
+ const messages = [...(fake.thread().messages as unknown[])];
+ messages[index] = { ...(messages[index] as object), touched: true };
+ return messages;
+}
+
+test("a keystroke reaches no row, any other composer or scope change reaches every row", () => {
+ const fake = fakeClient();
+ const rows = subscribeRows(fake, 4);
+
+ fake.publish({
+ composer: { ...fake.composer(), text: "h", isEmpty: false, queue: [] },
+ });
+ fake.publish({ composer: { ...fake.composer(), text: "hi", queue: [] } });
+ assert.deepEqual(rows.heard, [0, 0, 0, 0]);
+
+ fake.publish({
+ composer: { ...fake.composer(), attachments: [{ id: "a" }] },
+ });
+ assert.deepEqual(
+ rows.heard,
+ [1, 1, 1, 1],
+ "an attachment change is not a keystroke",
+ );
+
+ fake.publish({
+ composer: { ...fake.composer(), dictation: { inputDisabled: true } },
+ });
+ assert.deepEqual(
+ rows.heard,
+ [2, 2, 2, 2],
+ "dictation state is not a keystroke",
+ );
+
+ fake.publish({ thread: { isRunning: true } });
+ assert.deepEqual(
+ rows.heard,
+ [3, 3, 3, 3],
+ "a run starting reaches every row",
+ );
+
+ fake.publish({ tools: { tools: { search: {} } } });
+ assert.deepEqual(
+ rows.heard,
+ [4, 4, 4, 4],
+ "a scope the gate knows nothing about is compared by identity",
+ );
+
+ fake.publish({ composer: { ...fake.composer(), text: "hi there" } });
+ assert.deepEqual(rows.heard, [4, 4, 4, 4]);
+ rows.release();
+});
+
+test("a streamed token reaches the last two rows only", () => {
+ const fake = fakeClient();
+ const rows = subscribeRows(fake, 4);
+ fake.publish({ thread: { messages: withMessage(fake, 3) } });
+ assert.deepEqual(rows.heard, [0, 0, 1, 1]);
+ rows.release();
+});
+
+test("a rebuilt messages array holding the same messages reaches every row only after a repository write", () => {
+ const fake = fakeClient();
+ const rows = subscribeRows(fake, 4);
+ const rebuilt = () => [...(fake.thread().messages as unknown[])];
+ fake.publish({ thread: { messages: rebuilt() } });
+ assert.deepEqual(rows.heard, [0, 0, 0, 0], "a store-only rebuild");
+ // A write on a hidden branch rebuilds the array without touching a visible message.
+ fake.publish({ thread: { messages: rebuilt() }, repositoryWrite: true });
+ assert.deepEqual(rows.heard, [1, 1, 1, 1]);
+ rows.release();
+});
+
+test("a rebuilt messages array reaches every row when the repository cannot be read", () => {
+ const fake = fakeClient();
+ const client = {
+ ...(fake.client as unknown as Record<string, unknown>),
+ thread: () => ({ getState: () => fake.thread() }),
+ } as unknown as AssistantClient;
+ const gate = createRowNotificationGate(client);
+ const heard = [0, 0];
+ const release = heard.map((_, index) =>
+ gate.row(index).subscribe(() => {
+ heard[index] += 1;
+ }),
+ );
+ fake.publish({
+ thread: { messages: [...(fake.thread().messages as unknown[])] },
+ });
+ assert.deepEqual(heard, [1, 1]);
+ for (const r of release) r();
+});
+
+test("a non-empty queue change reaches every row", () => {
+ const fake = fakeClient();
+ const rows = subscribeRows(fake, 2);
+ fake.publish({ composer: { ...fake.composer(), queue: [{ id: "q" }] } });
+ assert.deepEqual(rows.heard, [1, 1]);
+ rows.release();
+});
+
+test("a changed message reaches its own row, the one before it and every later row", () => {
+ const fake = fakeClient();
+ const rows = subscribeRows(fake, 4);
+ fake.publish({ thread: { messages: withMessage(fake, 2) } });
+ assert.deepEqual(rows.heard, [0, 1, 1, 1]);
+ fake.publish({ thread: { messages: withMessage(fake, 0) } });
+ assert.deepEqual(rows.heard, [1, 2, 2, 2]);
+ rows.release();
+});
+
+test("a message added or removed reaches every row", () => {
+ const fake = fakeClient();
+ const rows = subscribeRows(fake, 4);
+ fake.publish({
+ thread: {
+ messages: [...(fake.thread().messages as unknown[]), { id: "m4" }],
+ },
+ });
+ assert.deepEqual(rows.heard, [1, 1, 1, 1]);
+ fake.publish({
+ thread: { messages: (fake.thread().messages as unknown[]).slice(1) },
+ });
+ assert.deepEqual(rows.heard, [2, 2, 2, 2]);
+ rows.release();
+});
+
+test("a fingerprint that throws reaches every row", () => {
+ const fake = fakeClient();
+ let broken = false;
+ const client = new Proxy(fake.client as object, {
+ ownKeys(target) {
+ if (broken) throw new Error("boom");
+ return Reflect.ownKeys(target);
+ },
+ }) as AssistantClient;
+ const gate = createRowNotificationGate(client);
+ const heard = [0, 0];
+ const release = heard.map((_, index) =>
+ gate.row(index).subscribe(() => {
+ heard[index] += 1;
+ }),
+ );
+ const original = console.error;
+ console.error = () => {};
+ try {
+ broken = true;
+ fake.publish({ composer: { ...fake.composer(), text: "x" } });
+ } finally {
+ console.error = original;
+ }
+ assert.deepEqual(heard, [1, 1]);
+ for (const r of release) r();
+});
+
+test("the gate holds the parent subscription only while a row is subscribed", () => {
+ const fake = fakeClient();
+ const gate = createRowNotificationGate(fake.client);
+ assert.equal(fake.parentSubscriptions(), 0);
+ const a = gate.row(0).subscribe(() => {});
+ const b = gate.row(1).subscribe(() => {});
+ assert.equal(fake.parentSubscriptions(), 1);
+ a();
+ assert.equal(fake.parentSubscriptions(), 1);
+ b();
+ assert.equal(fake.parentSubscriptions(), 0);
+});
+
+test("a row client is stable per index and inherits every scope from its parent", () => {
+ const fake = fakeClient();
+ const gate = createRowNotificationGate(fake.client);
+ assert.equal(gate.row(2), gate.row(2));
+ const row = gate.row(2) as unknown as Record<
+ string,
+ () => { getState: () => State }
+ >;
+ assert.equal(row.thread().getState(), fake.thread());
+ assert.notEqual(
+ (row as unknown as AssistantClient).subscribe,
+ fake.client.subscribe,
+ );
+});