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 message delete from re-rendering the whole thread (#9042)

Daniel Han98994b9921ab
diff --git a/studio/frontend/src/components/assistant-ui/research-reply-owners.ts b/studio/frontend/src/components/assistant-ui/research-reply-owners.ts
new file mode 100644
index 00000000000..8c7b2f80fd4
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/research-reply-owners.ts
@@ -0,0 +1,53 @@
+// 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 messages own a research reply, answered once per thread revision instead of once per
+ * message.
+ *
+ * A reply can sit on a branch the view is not showing, so this needs the whole repository, not
+ * the visible message list. Every user message's action bar asks it, and one export per message
+ * made any thread change quadratic in thread length -- paid on every delete and every generated
+ * token. One pass per revision removes the per-message factor (not the export itself).
+ *
+ * Keyed on the revision ALONE, so it assumes ONE question: a second caller asking something else
+ * of the same repository would get this answer. Give it its own map, not a second predicate.
+ */
+
+export type ExportedReplyItem = {
+ parentId: string | null;
+ message: { metadata?: unknown };
+};
+
+// Keyed on the revision object, not a counter, so a stale entry is unreachable: a current
+// revision is the same object, a stale one has been replaced. Weak, so a dead thread's entry goes
+// with it.
+const ownersByRevision = new WeakMap<object, ReadonlySet<string>>();
+
+/**
+ * Ids of the messages that have at least one research reply.
+ *
+ * @param revision identity that changes whenever the exported repository could have. assistant-ui
+ * rebuilds its message array on every repository mutation (add, delete, branch switch, reset),
+ * so that array is one.
+ * @param exportItems reads the repository. Called at most once per revision.
+ * @param isResearchReply whether a message's metadata marks it as a research reply.
+ */
+export function researchReplyOwners(
+ revision: object,
+ exportItems: () => readonly ExportedReplyItem[],
+ isResearchReply: (metadata: unknown) => boolean,
+): ReadonlySet<string> {
+ const known = ownersByRevision.get(revision);
+ if (known) {
+ return known;
+ }
+ const owners = new Set<string>();
+ for (const { parentId, message } of exportItems()) {
+ if (parentId !== null && isResearchReply(message.metadata)) {
+ owners.add(parentId);
+ }
+ }
+ ownersByRevision.set(revision, owners);
+ return owners;
+}
diff --git a/studio/frontend/src/components/assistant-ui/thread-message-slot.ts b/studio/frontend/src/components/assistant-ui/thread-message-slot.ts
new file mode 100644
index 00000000000..9272a6102cd
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/thread-message-slot.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * How the thread hands one message to a component, and which component that is.
+ *
+ * ThreadPrimitive.Messages rebuilds its element array whenever the message COUNT changes, so one
+ * delete re-renders every remaining message's wrapper. assistant-ui absorbs that in
+ * RenderChildrenWithAccessor: a render prop returning a PROPLESS element gets the same element
+ * object back every render, and React skips that subtree. The `components={{...}}` form never
+ * reaches the bail-out -- it returns `<ThreadMessageComponent components={...} />`, whose props
+ * object is freshly allocated each time, so a delete re-renders every body, action bar and
+ * tooltip in the thread.
+ */
+
+import { type ComponentType, type ReactElement, createElement } from "react";
+
+export type ThreadMessageRole = "user" | "assistant" | "system";
+
+/** Which of the thread's message components renders a message in this state. */
+export type ThreadMessageKind = "edit" | "user" | "assistant" | "none";
+
+/**
+ * Pick the component for a message.
+ *
+ * assistant-ui's own getComponent fallback chain, resolved for the three components the thread
+ * supplies (UserMessage, AssistantMessage, EditComposer) and no others:
+ *
+ * - editing wins over role: every role's *EditComposer falls back to EditComposer, the only
+ * one supplied.
+ * - an unedited system message falls back SystemMessage -> Message -> a default that renders
+ * nothing, and neither is supplied.
+ */
+export function threadMessageKind(
+ role: ThreadMessageRole,
+ isEditing: boolean,
+): ThreadMessageKind {
+ if (isEditing) {
+ return "edit";
+ }
+ if (role === "user") {
+ return "user";
+ }
+ if (role === "assistant") {
+ return "assistant";
+ }
+ return "none";
+}
+
+/**
+ * A render prop that always returns the SAME propless element for `Component`.
+ *
+ * Propless is what assistant-ui's bail-out requires; one shared instance also makes the bail-out
+ * React's own, since React skips a child whose element is identical to the one it rendered. That
+ * needs the element built once, here -- createElement per render returns a new object each time.
+ */
+export function proplessSlot(Component: ComponentType): () => ReactElement {
+ const element = createElement(Component);
+ return () => element;
+}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index e515c56e5d6..c4c856b007d 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -19,7 +19,12 @@ import {
import { MessageTiming } from "@/components/assistant-ui/message-timing";
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";
import { Sources, SourcesGroup } from "@/components/assistant-ui/sources";
+import {
+ proplessSlot,
+ threadMessageKind,
+} from "@/components/assistant-ui/thread-message-slot";
import {
thinkEffortAriaLabel,
thinkToggleAriaLabel,
@@ -1461,6 +1466,29 @@ const FOOTER_GAP_BELOW_SPACER_PX = 10;
// Covers instant responses where isRunning is already false by resize time.
const RUN_SHRINK_WINDOW_MS = 1000;
+// One message, picked from its role and edit state rather than from a `components` map. See
+// thread-message-slot.ts for why the map form costs a full-thread re-render on every delete.
+// The selectors are ThreadMessageComponent's own, so what a message subscribes to is unchanged.
+const ThreadMessage: FC = () => {
+ const role = useAuiState(({ message }) => message.role);
+ const isEditing = useAuiState(({ message }) => message.composer.isEditing);
+ switch (threadMessageKind(role, isEditing)) {
+ case "edit":
+ return <EditComposer />;
+ case "user":
+ return <UserMessage />;
+ case "assistant":
+ return <AssistantMessage />;
+ default:
+ return null;
+ }
+};
+
+// Hoisted, so ThreadPrimitive.Messages sees the same children function on every Thread render. An
+// inline arrow changes identity each time, invalidating the memo that keeps the message array from
+// being rebuilt, and the bail-out below it would never get to run.
+const renderThreadMessage = proplessSlot(ThreadMessage);
+
// 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<{
@@ -1709,13 +1737,9 @@ export const Thread: FC<{
</AuiIf>
)}
- <ThreadPrimitive.Messages
- components={{
- UserMessage,
- EditComposer,
- AssistantMessage,
- }}
- />
+ <ThreadPrimitive.Messages>
+ {renderThreadMessage}
+ </ThreadPrimitive.Messages>
{/* Bottom slack so the last message has room above the sticky
scroll-to-bottom button (and floating composer in single mode),
@@ -6701,20 +6725,28 @@ const useResearchMessageRunId = () => {
return useAuiState(({ message }) => getResearchRunId(message.metadata));
};
+// Boolean(), not `!== null`: getResearchRunId returns whatever string it found, and an empty one
+// counted as "no research reply" before. Keeping that stops an empty id hiding a message's edit
+// and delete controls.
+const hasResearchRunId = (metadata: unknown): boolean =>
+ Boolean(getResearchRunId(metadata));
+
const useOwnsResearchMessage = () => {
const aui = useAui();
const messageId = useAuiState(({ message }) => message.id);
- const messages = useAuiState(({ thread }) => thread.messages);
- if (messages.length === 0) {
- return false;
- }
- return aui
- .thread()
- .export()
- .messages.some(
- ({ parentId, message }) =>
- parentId === messageId && Boolean(getResearchRunId(message.metadata)),
- );
+ // The ANSWER is selected, not the message array: selecting the array subscribed every user
+ // message's action bar (and its tooltips) to every thread change, so one delete re-rendered all
+ // of them even when the answer had not moved. The export is shared across one revision.
+ return useAuiState(({ thread }) => {
+ if (thread.messages.length === 0) {
+ return false;
+ }
+ return researchReplyOwners(
+ thread.messages,
+ () => aui.thread().export().messages,
+ hasResearchRunId,
+ ).has(messageId);
+ });
};
// Whether the active thread has a non-terminal durable research run. After a reload the
diff --git a/studio/frontend/tests/research-reply-owners.test.ts b/studio/frontend/tests/research-reply-owners.test.ts
new file mode 100644
index 00000000000..c3e71fc4ee7
--- /dev/null
+++ b/studio/frontend/tests/research-reply-owners.test.ts
@@ -0,0 +1,86 @@
+// 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 user message's action bar asks whether it owns a research reply. The answer needs the
+// whole repository, not the visible message list, because a reply can sit on a branch the view is
+// not showing. One export per message made every thread change quadratic in thread length, paid
+// on every delete and every generated token.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ type ExportedReplyItem,
+ researchReplyOwners,
+} from "../src/components/assistant-ui/research-reply-owners.ts";
+
+const research = (id: string) => ({ custom: { researchRunId: id } });
+
+function items(): ExportedReplyItem[] {
+ return [
+ { parentId: null, message: { metadata: {} } },
+ { parentId: "prompt-1", message: { metadata: research("run-a") } },
+ { parentId: "prompt-2", message: { metadata: {} } },
+ // A second reply under the same prompt, on another branch. The visible list holds at most one
+ // of them, which is why this cannot be answered from thread.messages.
+ { parentId: "prompt-1", message: { metadata: research("run-b") } },
+ ];
+}
+
+const isResearch = (metadata: unknown) =>
+ typeof (metadata as { custom?: { researchRunId?: unknown } } | undefined)
+ ?.custom?.researchRunId === "string";
+
+test("collects the parents of research replies and nothing else", () => {
+ const owners = researchReplyOwners({}, items, isResearch);
+
+ assert.ok(owners.has("prompt-1"));
+ // Has a reply, but not a research one.
+ assert.ok(!owners.has("prompt-2"));
+ assert.equal(owners.size, 1);
+});
+
+test("a rootless research reply names no owner", () => {
+ const owners = researchReplyOwners(
+ {},
+ () => [{ parentId: null, message: { metadata: research("run-a") } }],
+ isResearch,
+ );
+
+ assert.equal(owners.size, 0);
+});
+
+test("one export serves every message at the same revision", () => {
+ const revision = {};
+ let exports = 0;
+ const read = () => {
+ exports += 1;
+ return items();
+ };
+
+ // Stands in for a thread's action bars: each asks about its own message, at one revision.
+ for (const messageId of ["prompt-1", "prompt-2", "prompt-3"]) {
+ researchReplyOwners(revision, read, isResearch).has(messageId);
+ }
+
+ assert.equal(exports, 1);
+});
+
+test("a new revision is exported again, and sees the change", () => {
+ const before = researchReplyOwners({}, items, isResearch);
+ assert.ok(before.has("prompt-1"));
+
+ let exports = 0;
+ const after = researchReplyOwners(
+ {},
+ () => {
+ exports += 1;
+ // The research reply has been deleted.
+ return items().filter(({ parentId }) => parentId !== "prompt-1");
+ },
+ isResearch,
+ );
+
+ assert.equal(exports, 1);
+ assert.ok(!after.has("prompt-1"));
+});
diff --git a/studio/frontend/tests/thread-delete-render-budget.test.ts b/studio/frontend/tests/thread-delete-render-budget.test.ts
new file mode 100644
index 00000000000..34e76dc53ef
--- /dev/null
+++ b/studio/frontend/tests/thread-delete-render-budget.test.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Deleting one message used to re-render every message in the thread, so a delete cost grew with
+// thread length: 98ms at 25K characters of content, 472ms at 300K.
+//
+// The fix is invisible in the rendered output -- the DOM is identical either way, only how much
+// of the tree React walks differs. So, like research-render-budget.test.ts and
+// drag-costs-no-render.test.ts, the wiring is pinned at the source: assert the cheap path, assert
+// the expensive one is gone. Each of the three seams below is silently load-bearing: undo any one
+// and the thread still renders correctly, the unit tests beside this file still pass, and the
+// delete is linear in thread length again.
+
+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 thread = source("components/assistant-ui/thread.tsx");
+
+function block(start: string): string {
+ const [, rest] = thread.split(start, 2);
+ assert.ok(rest !== undefined, `thread.tsx no longer contains ${start}`);
+ const [body] = (rest ?? "").split("\n};", 1);
+ return body ?? "";
+}
+
+test("the message list is rendered through a render prop, not a components map", () => {
+ // assistant-ui only skips a message subtree when the render prop's element has no props, and
+ // the map form returns <ThreadMessageComponent components={...} />, whose props object is
+ // freshly allocated per render.
+ assert.match(
+ thread,
+ /<ThreadPrimitive\.Messages>\s*\{renderThreadMessage\}\s*<\/ThreadPrimitive\.Messages>/,
+ );
+ assert.doesNotMatch(thread, /<ThreadPrimitive\.Messages[^>]*\scomponents=/s);
+});
+
+test("the render prop is built once, at module scope", () => {
+ // ThreadPrimitive.Messages memoizes on children identity, so an arrow written inline in Thread
+ // would be a new function per Thread render: the message array would be rebuilt from scratch
+ // each time, leaving nothing for the bail-out to skip.
+ assert.match(
+ thread,
+ /^const renderThreadMessage = proplessSlot\(ThreadMessage\);$/m,
+ );
+});
+
+test("ThreadMessage sends each kind to the component that names it", () => {
+ const body = block("const ThreadMessage: FC = () => {");
+ assert.match(body, /threadMessageKind\(role, isEditing\)/);
+ assert.match(body, /case "edit":\s*return <EditComposer \/>;/);
+ assert.match(body, /case "user":\s*return <UserMessage \/>;/);
+ assert.match(body, /case "assistant":\s*return <AssistantMessage \/>;/);
+ assert.match(body, /default:\s*return null;/);
+});
+
+test("research-reply ownership is selected as an answer, not as the message list", () => {
+ const hook = block("const useOwnsResearchMessage = () => {");
+ // Selecting the array subscribed every user message's action bar to every thread change, so one
+ // delete re-rendered all of them along with their tooltips.
+ assert.doesNotMatch(
+ hook,
+ /useAuiState\(\(\{ thread \}\) => thread\.messages\)/,
+ );
+ // The revision key must be the array the store hands out. A copy is a new object per read, so
+ // the memo would never hit and a full repository export would be back inside every getSnapshot,
+ // worse than what this replaced.
+ assert.match(hook, /researchReplyOwners\(\s*thread\.messages,/);
+ assert.doesNotMatch(
+ hook,
+ /researchReplyOwners\(\s*\[\.\.\.thread\.messages\]/,
+ );
+});
diff --git a/studio/frontend/tests/thread-message-slot.test.ts b/studio/frontend/tests/thread-message-slot.test.ts
new file mode 100644
index 00000000000..bc20c2364bb
--- /dev/null
+++ b/studio/frontend/tests/thread-message-slot.test.ts
@@ -0,0 +1,63 @@
+// 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 thread renders a message through a render prop rather than assistant-ui's `components` map,
+// so the returned element can be the same object every time. That is what lets React skip a
+// message subtree when the message COUNT changes, which is what a delete does to every remaining
+// message.
+//
+// Two things must hold, and neither shows in the DOM: the component choice has to match the
+// fallback chain the `components` map resolved through, and the element has to be shared.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createElement } from "react";
+
+import {
+ proplessSlot,
+ threadMessageKind,
+} from "../src/components/assistant-ui/thread-message-slot.ts";
+
+test("editing wins over role, for every role", () => {
+ assert.equal(threadMessageKind("user", true), "edit");
+ assert.equal(threadMessageKind("assistant", true), "edit");
+ // In the map form this resolved SystemEditComposer -> EditComposer, the only one supplied.
+ assert.equal(threadMessageKind("system", true), "edit");
+});
+
+test("a message that is not being edited goes to its role's component", () => {
+ assert.equal(threadMessageKind("user", false), "user");
+ assert.equal(threadMessageKind("assistant", false), "assistant");
+});
+
+test("a system message that is not being edited renders nothing", () => {
+ // SystemMessage -> Message -> assistant-ui's default, which returns null. Neither was supplied,
+ // so a system message has never had a body here; giving it one would put an unstyled message
+ // into every thread with a system prompt.
+ assert.equal(threadMessageKind("system", false), "none");
+});
+
+test("the slot hands back one shared element rather than a new one per render", () => {
+ const Component = () => null;
+ const slot = proplessSlot(Component);
+
+ const first = slot();
+ const second = slot();
+
+ // Identity, not equality: React skips a child whose element is the very object it rendered last
+ // time. A fresh element with identical contents is re-rendered instead.
+ assert.equal(first, second);
+ assert.notEqual(first, createElement(Component));
+});
+
+test("the slot's element carries no props", () => {
+ const Component = () => null;
+ const element = proplessSlot(Component)();
+
+ assert.equal(element.type, Component);
+ // assistant-ui's RenderChildrenWithAccessor only memoizes a PROPLESS element: it keys on the
+ // props object, freshly allocated per render as soon as there is one prop to put in it. That is
+ // how the `components={{...}}` form lost the bail-out.
+ assert.deepEqual(Object.keys(element.props as object), []);
+});
diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.py
index 67a41f71aa9..2259e28f1f0 100644
--- a/tests/studio/test_deep_research_frontend_contract.py
+++ b/tests/studio/test_deep_research_frontend_contract.py
@@ -155,7 +155,18 @@ def test_research_presentation_is_integrated() -> None:
assert "if (researchRunId) return null" in thread
assert "!researchRunId &&" in thread
assert "if (researchRunId || ownsResearchMessage)" in thread
- assert "parentId === messageId && Boolean(getResearchRunId(message.metadata))" in thread
+ # A prompt whose reply is a research message loses its edit and delete controls. Ownership is
+ # a question about the whole repository, not the visible message list: a reply can sit on a
+ # branch the view is not showing. It used to be one export per user message (quadratic in
+ # thread length); the answer is now shared across the thread, so what is pinned here is the
+ # question and its scope rather than the expression that computed it.
+ owners = source("components/assistant-ui/research-reply-owners.ts")
+ assert "researchReplyOwners(" in thread
+ assert "() => aui.thread().export().messages" in thread
+ # An empty run id still means "no research reply", as Boolean() rather than a null check.
+ assert "Boolean(getResearchRunId(metadata))" in thread
+ assert "isResearchReply(message.metadata)" in owners
+ assert "owners.add(parentId)" in owners
user_actions = thread.split("const UserActionBar: FC = () =>", 1)[1].split(
"const EditComposer:", 1
)[0]