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.

Reduce scrolling lag in long chats by bounding offscreen reply painting (#16782)

Lee Jacksona17436bde0ae
diff --git a/studio/frontend/src/components/assistant-ui/reply-paint.ts b/studio/frontend/src/components/assistant-ui/reply-paint.ts
new file mode 100644
index 00000000000..4315c9faea2
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/reply-paint.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Keep the normal overflow of replies near the user (focus rings, menus and wide math).
+// One observer per scroller also handles side-by-side threads independently.
+const observers = new WeakMap<Element, IntersectionObserver>();
+// Width or font changes do not cross the observer margin, so recheck sizes too.
+const resizers = new WeakMap<Element, ResizeObserver>();
+
+export function observeReplyPaint(reply: HTMLElement) {
+ const viewport = reply.closest(".aui-thread-viewport");
+ if (!viewport || typeof IntersectionObserver === "undefined") return;
+
+ let observer = observers.get(viewport);
+ if (!observer) {
+ observer = new IntersectionObserver((entries) => {
+ // Read before writing any styles. A wide reply can own the thread's horizontal
+ // scroll range even while it's well above or below the visible conversation.
+ const distant = entries.map(({ target, boundingClientRect, rootBounds }) =>
+ rootBounds !== null &&
+ (boundingClientRect.bottom < rootBounds.top || boundingClientRect.top > rootBounds.bottom) &&
+ target.scrollWidth <= target.clientWidth
+ );
+ entries.forEach(({ target }, i) => target.toggleAttribute("data-reply-paint", distant[i]));
+ }, { root: viewport, rootMargin: "1500px 0px" });
+ observers.set(viewport, observer);
+ }
+ observer.observe(reply);
+
+ let resizer = resizers.get(viewport);
+ if (!resizer && typeof ResizeObserver !== "undefined") {
+ resizer = new ResizeObserver((entries) => {
+ // Only a bounded reply can lose an exemption it now needs; unbounded ones wait for the
+ // intersection observer. Read every width before removing any attribute.
+ const wide = entries.map(({ target }) =>
+ target.hasAttribute("data-reply-paint") && target.scrollWidth > target.clientWidth
+ );
+ entries.forEach(({ target }, i) => {
+ if (wide[i]) target.removeAttribute("data-reply-paint");
+ });
+ });
+ resizers.set(viewport, resizer);
+ }
+ resizer?.observe(reply);
+ return () => {
+ observer.unobserve(reply);
+ resizer?.unobserve(reply);
+ reply.removeAttribute("data-reply-paint");
+ };
+}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 882616e30c0..f38f6dd7250 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -52,6 +52,7 @@ import {
import { ComposerDraftPreview } from "@/components/assistant-ui/composer-draft-preview";
import { PromptQueueList } from "@/components/assistant-ui/lazy-prompt-queue-list";
import { QueueResumeIcon } from "@/components/assistant-ui/queue-resume-icon";
+import { observeReplyPaint } from "@/components/assistant-ui/reply-paint";
import { ProgressiveMessages } from "@/components/assistant-ui/progressive-messages";
import { MessageMenuTime } from "@/components/assistant-ui/message-menu-time";
import { AssistantMessageTime } from "@/components/assistant-ui/assistant-message-time";
@@ -8270,6 +8271,10 @@ const ResearchMessageRunIdContext = createContext<string | null>(null);
const AssistantMessage: FC = () => {
const aui = useAui();
const focusReveal = useActionBarFocusReveal();
+ const replyRef = focusReveal.ref;
+ useEffect(() => {
+ if (replyRef.current) return observeReplyPaint(replyRef.current);
+ }, [replyRef]);
const messageId = useAuiState(({ message }) => message.id);
const messageContent = useAuiState(({ message }) =>
"status" in message && message.status?.type === "running"
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 54bf7c053dd..32eee5a9baf 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -4288,6 +4288,14 @@ html[data-chat-font] .aui-root {
font-family: var(--font-sans);
}
+ /* Distant, horizontally fitting replies can paint independently while keeping
+ their natural layout and searchable text. Print uses normal page overflow. */
+ @media screen {
+ .aui-assistant-message-root[data-reply-paint] {
+ contain: paint;
+ }
+ }
+
/* Zero the trailing margin along the deepest :last-child path (streamdown nests 4-5 levels) so the
gap above the action bar is only the footer's mt-*; a generic descendant rule would hit lists. */
.aui-assistant-message-content > *:last-child,
diff --git a/studio/frontend/tests/reply-paint.test.ts b/studio/frontend/tests/reply-paint.test.ts
new file mode 100644
index 00000000000..d672e7ca4ec
--- /dev/null
+++ b/studio/frontend/tests/reply-paint.test.ts
@@ -0,0 +1,62 @@
+// 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 { readFileSync } from "node:fs";
+import vm from "node:vm";
+import test from "node:test";
+import ts from "@typescript/typescript6";
+
+const source = readFileSync(new URL("../src/components/assistant-ui/reply-paint.ts", import.meta.url), "utf8");
+const { outputText } = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } });
+
+class Reply {
+ attributes = new Set<string>();
+ scrollWidth = 600;
+ clientWidth = 600;
+ viewport: object;
+ constructor(viewport: object) { this.viewport = viewport; }
+ closest(selector: string) { return selector === ".aui-thread-viewport" ? this.viewport : null; }
+ hasAttribute(name: string) { return this.attributes.has(name); }
+ removeAttribute(name: string) { this.attributes.delete(name); }
+ toggleAttribute(name: string, on: boolean) { if (on) this.attributes.add(name); else this.attributes.delete(name); }
+}
+
+function world() {
+ let intersect: (entries: unknown[]) => void = () => {};
+ let resize: (entries: Array<{ target: Reply }>) => void = () => {};
+ const resized = new Set<Reply>();
+ const exports: { observeReplyPaint?: (reply: Reply) => (() => void) | undefined } = {};
+ vm.runInNewContext(outputText, {
+ exports,
+ IntersectionObserver: class { constructor(cb: typeof intersect) { intersect = cb; } observe() {} unobserve() {} },
+ ResizeObserver: class {
+ constructor(cb: typeof resize) { resize = cb; }
+ observe(target: Reply) { resized.add(target); }
+ unobserve(target: Reply) { resized.delete(target); }
+ },
+ });
+ const rootBounds = { top: 0, bottom: 800 };
+ return {
+ observe: exports.observeReplyPaint!,
+ distant: (reply: Reply) => intersect([{ target: reply, rootBounds, boundingClientRect: { top: 5000, bottom: 5600 } }]),
+ resize: (...targets: Reply[]) => resize(targets.map((target) => ({ target }))),
+ resized,
+ };
+}
+
+test("a bounded reply that becomes wide off screen gets its overflow back without an intersection", () => {
+ const w = world(), viewport = {}, reply = new Reply(viewport), other = new Reply(viewport);
+ const stop = w.observe(reply)!;
+ w.observe(other);
+ w.distant(reply);
+ w.distant(other);
+ assert.equal(reply.hasAttribute("data-reply-paint"), true, "a distant, fitting reply is bounded");
+ // The chat column narrowed: `reply` now overflows, `other` still fits.
+ reply.clientWidth = 400;
+ w.resize(reply, other);
+ assert.equal(reply.hasAttribute("data-reply-paint"), false, "the wide-reply exemption applies at once");
+ assert.equal(other.hasAttribute("data-reply-paint"), true, "a reply that still fits stays bounded");
+ stop();
+ assert.equal(w.resized.has(reply), false, "cleanup stops watching the reply's size");
+});
diff --git a/tests/studio/playwright_long_chat_renders.py b/tests/studio/playwright_long_chat_renders.py
index b3e01f342cf..946158111fa 100644
--- a/tests/studio/playwright_long_chat_renders.py
+++ b/tests/studio/playwright_long_chat_renders.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Render counts while a reply streams into a chat with tool cards and web sources.
+"""Check rendering during streaming and scrolling in a long chat with tools and web sources.
A streamed token must not re-render the reply's source badges, and a run starting or ending
must not re-render the python / terminal cards of earlier replies. Counts come from a React
@@ -15,7 +15,7 @@ import os
import sys
from pathlib import Path
-from playwright.sync_api import sync_playwright
+from playwright.sync_api import expect, sync_playwright
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _playwright_robust import ( # noqa: E402
@@ -106,6 +106,31 @@ def run(page) -> dict[str, int]:
return counts
+def check_reply_paint(page) -> None:
+ viewport = page.locator(".aui-thread-viewport")
+ replies = page.locator('[data-role="assistant"]')
+ # The first two replies are neighbors. One will contain a wide unwrapped block.
+ first, second = replies.nth(0), replies.nth(1)
+ scroll = "(v, end) => v.scrollTo({top: end ? v.scrollHeight : 0, behavior: 'instant'})"
+ viewport.evaluate(scroll, True)
+ expect(second).to_have_css("contain", "paint")
+ page.emulate_media(media = "print")
+ expect(second).to_have_css("contain", "none")
+ page.emulate_media(media = "screen")
+
+ viewport.evaluate(scroll, False)
+ expect(first).to_have_css("contain", "none")
+ expect(second).to_have_css("contain", "none")
+ first.locator(".aui-assistant-message-content").evaluate("e => e.style.minWidth = '200vw'")
+ viewport.evaluate(scroll, True)
+ expect(second).to_have_css("contain", "paint")
+ assert first.evaluate("e => e.scrollWidth > e.clientWidth"), "fixture has no wide reply"
+ expect(first).to_have_css("contain", "none")
+ assert viewport.evaluate(
+ "v => v.scrollWidth > v.clientWidth"
+ ), "wide reply lost its horizontal scroll range"
+
+
def main() -> int:
proc = None
try:
@@ -126,6 +151,7 @@ def main() -> int:
errors: list[str] = []
page.on("pageerror", lambda error: errors.append(str(error)))
counts = run(page)
+ check_reply_paint(page)
finally:
browser.close()
badges = counts.get("SourceBadge", 0)
diff --git a/tests/studio/studiobench/scene/parity.js b/tests/studio/studiobench/scene/parity.js
index fb59de0e322..e91a48933ec 100644
--- a/tests/studio/studiobench/scene/parity.js
+++ b/tests/studio/studiobench/scene/parity.js
@@ -25,7 +25,10 @@
const ID_ATTR_RE = /^data-[a-z0-9-]+-id$/;
const isVolatile = (name) => VOLATILE_ATTRS.has(name) || ID_ATTR_RE.test(name);
- const IGNORED_ATTRS = new Set(["data-react-checksum", "data-reactroot"]);
+ // data-reply-paint is a paint-containment hint toggled by an IntersectionObserver on replies
+ // that are far from the viewport: it carries no content and its presence depends on scroll
+ // position, so it is not thread structure.
+ const IGNORED_ATTRS = new Set(["data-react-checksum", "data-reactroot", "data-reply-paint"]);
// Dropped only from the visible-region digest; see parityVisible.capture().
const VIRTUALIZATION_ATTRS = new Set(["aria-posinset", "aria-setsize"]);