Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(chat): let the follower claim its own scrolls

M3gA-Mindbc3aa0e5ba8f
diff --git a/app/src/components/assistant-ui/thread.followBottom.test.tsx b/app/src/components/assistant-ui/thread.followBottom.test.tsx
new file mode 100644
index 0000000000..f9327a0e67
--- /dev/null
+++ b/app/src/components/assistant-ui/thread.followBottom.test.tsx
@@ -0,0 +1,286 @@
+/**
+ * `useFollowBottom` — the contract, at unit level.
+ *
+ * The e2e specs cover the integrated behaviour but they missed a real defect:
+ * the turn-start alignment (`scrollIntoView({ block: 'start' })`) scrolls UP,
+ * which the follow listener read as the reader leaving the bottom. E2E did not
+ * catch it because the listener checks proximity first, and after a SHORT user
+ * message the viewport is still within the 80px threshold — so the bug only
+ * appears for a user message tall enough to push past it. A browser test would
+ * need a fixture sized to that boundary; here the geometry is set directly.
+ *
+ * jsdom performs no layout, so every metric is assigned explicitly and the
+ * observable is the imperative `scrollTo` call, not a resulting `scrollTop` —
+ * the same approach as `thread.openScroll.test.tsx`.
+ */
+import { AssistantUiRuntimeProvider } from '@/providers/AssistantUiRuntimeProvider';
+import chatRuntimeReducer from '@/store/chatRuntimeSlice';
+import threadReducer, { loadThreadMessages } from '@/store/threadSlice';
+import type { ThreadMessage } from '@/types/thread';
+import { configureStore } from '@reduxjs/toolkit';
+import { render } from '@testing-library/react';
+import { act } from 'react';
+import { Provider } from 'react-redux';
+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
+
+import { Thread } from './thread';
+
+vi.mock('@/services/api/threadApi', () => ({
+ threadApi: { getDerivedTranscript: vi.fn().mockResolvedValue({ items: [], nextCursor: null }) },
+}));
+
+function msg(id: string, sender: 'user' | 'agent', content: string): ThreadMessage {
+ return {
+ id,
+ content,
+ type: 'text',
+ extraMetadata: {},
+ sender,
+ createdAt: `2026-09-23T00:00:${id.padStart(2, '0')}Z`,
+ };
+}
+
+function makeStore() {
+ return configureStore({ reducer: { thread: threadReducer, chatRuntime: chatRuntimeReducer } });
+}
+
+/**
+ * Capture every `ResizeObserver` callback the tree installs, so content growth
+ * can be simulated. The shared setup polyfills a no-op observer, which would
+ * make these tests vacuously green — nothing would ever fire.
+ */
+let resizeCallbacks: ResizeObserverCallback[] = [];
+let scrollToSpy: MockInstance;
+const RealResizeObserver = globalThis.ResizeObserver;
+
+beforeEach(() => {
+ resizeCallbacks = [];
+ globalThis.ResizeObserver = class {
+ constructor(cb: ResizeObserverCallback) {
+ resizeCallbacks.push(cb);
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ } as unknown as typeof ResizeObserver;
+ scrollToSpy = vi.spyOn(HTMLElement.prototype, 'scrollTo').mockImplementation(() => {});
+ vi.spyOn(Element.prototype, 'scrollIntoView').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ globalThis.ResizeObserver = RealResizeObserver;
+ vi.restoreAllMocks();
+});
+
+function viewportOf(container: HTMLElement): HTMLElement {
+ const el = container.querySelector<HTMLElement>('[data-slot="aui_thread-viewport"]');
+ if (!el) throw new Error('viewport not rendered');
+ return el;
+}
+
+/** jsdom reports 0 for every box, so the reader's position is set outright. */
+function setGeometry(el: HTMLElement, scrollTop: number, scrollHeight: number, clientHeight = 500) {
+ Object.defineProperty(el, 'scrollHeight', { value: scrollHeight, configurable: true });
+ Object.defineProperty(el, 'clientHeight', { value: clientHeight, configurable: true });
+ el.scrollTop = scrollTop;
+}
+
+/** Fire every captured resize callback, as a height change would. */
+function growContent() {
+ act(() => {
+ for (const cb of resizeCallbacks) cb([], {} as ResizeObserver);
+ });
+}
+
+function followedBottom(viewport: HTMLElement): boolean {
+ return scrollToSpy.mock.calls.some((call, i) => {
+ if (scrollToSpy.mock.contexts[i] !== viewport) return false;
+ const options = call[0] as ScrollToOptions | undefined;
+ return options?.top === viewport.scrollHeight;
+ });
+}
+
+function renderThread() {
+ const store = makeStore();
+ act(() => {
+ store.dispatch({
+ type: loadThreadMessages.fulfilled.type,
+ payload: { threadId: 't1', messages: [msg('1', 'user', 'hi'), msg('2', 'agent', 'hello')] },
+ });
+ });
+ const { container } = render(
+ <Provider store={store}>
+ <AssistantUiRuntimeProvider threadId="t1">
+ <Thread />
+ </AssistantUiRuntimeProvider>
+ </Provider>
+ );
+ return { container, store, viewport: viewportOf(container) };
+}
+
+describe('useFollowBottom', () => {
+ it('follows content growth for a reader at the bottom', () => {
+ const { viewport } = renderThread();
+ setGeometry(viewport, 500, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+ scrollToSpy.mockClear();
+
+ setGeometry(viewport, 500, 1400);
+ growContent();
+
+ expect(followedBottom(viewport)).toBe(true);
+ });
+
+ it('stops following once the reader scrolls up', () => {
+ const { viewport } = renderThread();
+ setGeometry(viewport, 500, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+
+ // Up, and past the 80px threshold — a deliberate move into history.
+ setGeometry(viewport, 100, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+ scrollToSpy.mockClear();
+
+ setGeometry(viewport, 100, 1400);
+ growContent();
+
+ expect(followedBottom(viewport)).toBe(false);
+ });
+
+ it('resumes following when the reader returns to the bottom', () => {
+ const { viewport } = renderThread();
+ // Start AT the bottom and scroll away, so following is genuinely off before
+ // the return is tested. Going straight to 100 from the initial baseline of
+ // 0 is an INCREASE, which never trips the clearing branch — the test would
+ // then pass with the proximity branch deleted.
+ setGeometry(viewport, 500, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+
+ setGeometry(viewport, 100, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+
+ setGeometry(viewport, 500, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+ scrollToSpy.mockClear();
+
+ setGeometry(viewport, 500, 1400);
+ growContent();
+
+ expect(followedBottom(viewport)).toBe(true);
+ });
+
+ it('keeps following after the turn-start alignment scrolls the viewport UP', () => {
+ // `ThreadBottomFollower` aligns a new user message with
+ // `scrollIntoView({ block: 'start' })`. For a reader at the bottom that
+ // LOWERS `scrollTop` — the message sits above the trailing margin and the
+ // status slot — which is indistinguishable from the reader moving into
+ // history unless the follower claims its own scroll.
+ //
+ // Ordering is the whole point: the alignment is synchronous, its `scroll`
+ // event is not. Setting the follow flag inside the effect is not enough,
+ // because the later event sees a drop against a stale baseline and clears
+ // it again. `claimScroll` re-baselines while `scrollTop` already holds the
+ // post-alignment value, so that event becomes a no-op.
+ //
+ // The e2e suite cannot reach this without a fixture sized to the 80px
+ // boundary: with a short user message the viewport stays within the
+ // threshold and the proximity branch masks it.
+ const { store, viewport } = renderThread();
+ setGeometry(viewport, 500, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+
+ // Make the alignment behave like the real one: `scrollIntoView` on a
+ // message above the trailing margin LOWERS `scrollTop`, synchronously,
+ // inside the effect. A no-op mock cannot reproduce the ordering this test
+ // exists to check — `claimScroll` would capture the pre-alignment value
+ // and the test would pass for the wrong reason.
+ vi.spyOn(Element.prototype, 'scrollIntoView').mockImplementation(() => {
+ viewport.scrollTop = 150;
+ });
+
+ act(() => {
+ store.dispatch({
+ type: loadThreadMessages.fulfilled.type,
+ payload: {
+ threadId: 't1',
+ messages: [
+ msg('1', 'user', 'hi'),
+ msg('2', 'agent', 'hello'),
+ msg('3', 'user', 'a tall follow-up question'),
+ ],
+ },
+ });
+ });
+
+ // The alignment's own scroll event arrives now.
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+ scrollToSpy.mockClear();
+
+ // The reply streams.
+ setGeometry(viewport, 150, 1600);
+ growContent();
+
+ expect(followedBottom(viewport)).toBe(true);
+ });
+
+ it('ignores the growth that prompted a claim, so the alignment survives', () => {
+ // The user message grows the content box, which queues a resize
+ // notification; the alignment then claims the scroll. Following that queued
+ // callback would scroll to the bottom and erase the alignment before it is
+ // painted — making it pointless rather than short-lived.
+ const { store, viewport } = renderThread();
+ setGeometry(viewport, 500, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+
+ vi.spyOn(Element.prototype, 'scrollIntoView').mockImplementation(() => {
+ viewport.scrollTop = 150;
+ });
+
+ // The new user message has already grown the box to 1400 when the alignment
+ // runs and claims at that height. `scrollTop` must put the reader AT the
+ // bottom (1400 - 500 clientHeight = 900), or `ThreadBottomFollower` returns
+ // early on its own proximity guard and never aligns or claims at all —
+ // which would make this test pass for the wrong reason.
+ setGeometry(viewport, 900, 1400);
+ act(() => {
+ store.dispatch({
+ type: loadThreadMessages.fulfilled.type,
+ payload: {
+ threadId: 't1',
+ messages: [
+ msg('1', 'user', 'hi'),
+ msg('2', 'agent', 'hello'),
+ msg('3', 'user', 'a tall follow-up question'),
+ ],
+ },
+ });
+ });
+ scrollToSpy.mockClear();
+
+ // The queued notification for THAT growth must not move the viewport.
+ growContent();
+ expect(followedBottom(viewport)).toBe(false);
+
+ // The reply arriving is growth beyond the claim, and is followed.
+ setGeometry(viewport, 150, 1900);
+ growContent();
+ expect(followedBottom(viewport)).toBe(true);
+ });
+
+ it('does not treat a growth-only scroll event as the reader leaving', () => {
+ const { viewport } = renderThread();
+ setGeometry(viewport, 500, 1000);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+
+ // The reply grew by more than the threshold and a queued `scroll` runs
+ // before the resize callback. `scrollTop` has NOT moved, so this must not
+ // clear the flag even though the distance now reads far from the bottom.
+ setGeometry(viewport, 500, 1400);
+ act(() => viewport.dispatchEvent(new Event('scroll')));
+ scrollToSpy.mockClear();
+
+ growContent();
+
+ expect(followedBottom(viewport)).toBe(true);
+ });
+});
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsx
index 9261d0fd2f..5ef59ee281 100644
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@ -82,6 +82,7 @@ import {
type FC,
type PropsWithChildren,
type RefObject,
+ useCallback,
useContext,
useEffect,
useLayoutEffect,
@@ -326,9 +327,14 @@ const ThreadRoot: FC<{
const { Welcome = ThreadWelcome } = useContext(ThreadComponentsContext);
const viewportRef = useRef<HTMLDivElement>(null);
const messageGroupRef = useRef<HTMLDivElement>(null);
+ // Everything the viewport scrolls over, which is MORE than the message group:
+ // the footer below it holds the follow-up suggestions, and those appear when
+ // a reply finishes. Observing only the messages misses that growth and leaves
+ // the transcript stranded short of the bottom at the end of every turn.
+ const scrollContentRef = useRef<HTMLDivElement>(null);
- useFollowBottom(viewportRef, messageGroupRef);
- useOpenThreadAtBottom(viewportRef);
+ const { claimScroll } = useFollowBottom(viewportRef, scrollContentRef);
+ useOpenThreadAtBottom(viewportRef, claimScroll);
return (
<ThreadPrimitive.Root
@@ -349,6 +355,7 @@ const ThreadRoot: FC<{
data-slot="aui_thread-viewport"
className="relative flex flex-1 flex-col overflow-x-auto overflow-y-scroll scroll-smooth">
<div
+ ref={scrollContentRef}
className={cn(
'mx-auto flex w-full max-w-(--thread-max-width) flex-1 flex-col px-4 pt-4',
isEmpty && 'justify-center'
@@ -376,7 +383,11 @@ const ThreadRoot: FC<{
<ThreadPrimitive.Messages>{() => <ThreadMessage />}</ThreadPrimitive.Messages>
<RunningStatusSlot />
</div>
- <ThreadBottomFollower viewportRef={viewportRef} contentRef={messageGroupRef} />
+ <ThreadBottomFollower
+ viewportRef={viewportRef}
+ contentRef={messageGroupRef}
+ claimScroll={claimScroll}
+ />
<ThreadPrimitive.ViewportFooter
className={cn(
@@ -446,7 +457,10 @@ const ThreadRoot: FC<{
* `viewportRef.current === null` on the mount that matters and would burn the
* latch without scrolling.
*/
-function useOpenThreadAtBottom(viewportRef: RefObject<HTMLDivElement | null>) {
+function useOpenThreadAtBottom(
+ viewportRef: RefObject<HTMLDivElement | null>,
+ claimScroll: () => void
+) {
const hasMessages = useAuiState(s => s.thread.messages.length > 0);
const threadId = useAuiThreadId();
// Which thread this viewport has already been dropped to the bottom for.
@@ -469,7 +483,14 @@ function useOpenThreadAtBottom(viewportRef: RefObject<HTMLDivElement | null>) {
// opening a thread should start at the bottom, not animate down through the
// entire history to get there.
viewport.scrollTo({ top: viewport.scrollHeight, behavior: 'instant' });
- }, [hasMessages, threadId, viewportRef]);
+ // Re-arm following for the NEW thread. `followRef` lives as long as this
+ // viewport, which outlives any one thread, so without this a reader who
+ // scrolled up in thread A carries that `false` into thread B — and if both
+ // threads sit at the same `scrollTop` (0 and 0 is the easy case) the open
+ // scroll produces no `scroll` event to re-enable it, so B never follows its
+ // own reply. Opening a thread is not a reader scrolling away from it.
+ claimScroll();
+ }, [claimScroll, hasMessages, threadId, viewportRef]);
}
const FOLLOW_BOTTOM_THRESHOLD_PX = 80;
@@ -522,6 +543,29 @@ function useFollowBottom(
// Starts true so a thread opens following; the first user scroll away from
// the bottom is what turns it off.
const followRef = useRef(true);
+ const lastScrollTopRef = useRef(0);
+ // `scrollHeight` as it stood when we last claimed a scroll. Growth up to this
+ // mark is growth we already knew about; only growth BEYOND it is new content
+ // worth following. `null` means no claim is outstanding.
+ const claimedHeightRef = useRef<number | null>(null);
+
+ /**
+ * Declare a scroll as OURS, after performing it.
+ *
+ * Setting `followRef` alone is not enough and was the first thing I tried.
+ * A programmatic scroll is synchronous but its `scroll` event is not, so the
+ * listener runs AFTER the caller has re-armed the flag, sees a `scrollTop`
+ * lower than the stale baseline, and clears it again. Re-baselining here —
+ * while `scrollTop` already holds the post-scroll value — is what makes the
+ * later event a no-op instead.
+ */
+ const claimScroll = useCallback(() => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+ lastScrollTopRef.current = viewport.scrollTop;
+ claimedHeightRef.current = viewport.scrollHeight;
+ followRef.current = true;
+ }, [viewportRef]);
useEffect(() => {
const viewport = viewportRef.current;
@@ -549,15 +593,15 @@ function useFollowBottom(
// event, so the reader's scroll away would be ignored and they would be
// dragged back down — breaking the "never yank a reader who left the
// bottom" contract. Keying on `scrollTop` alone holds in both cases.
- let lastScrollTop = viewport.scrollTop;
+ lastScrollTopRef.current = viewport.scrollTop;
const onScroll = () => {
if (distanceFromBottom() <= FOLLOW_BOTTOM_THRESHOLD_PX) {
followRef.current = true;
- } else if (viewport.scrollTop < lastScrollTop) {
+ } else if (viewport.scrollTop < lastScrollTopRef.current) {
followRef.current = false;
}
- lastScrollTop = viewport.scrollTop;
+ lastScrollTopRef.current = viewport.scrollTop;
};
viewport.addEventListener('scroll', onScroll, { passive: true });
@@ -575,6 +619,24 @@ function useFollowBottom(
// genuine upward move by the reader — see the note there for why a bare
// proximity test would clear it on the growth being reacted to.
if (!followRef.current) return;
+ // Do not follow the growth that PROMPTED the claim.
+ //
+ // A new user message grows the content box, which queues a resize
+ // notification; `ThreadBottomFollower` then aligns that message to the
+ // top and claims the scroll. The queued callback runs afterwards, and
+ // following it would scroll straight to the bottom — erasing the
+ // alignment before it is ever painted, which makes the alignment
+ // pointless rather than merely short-lived.
+ //
+ // So a claim records the height it was made at, and growth up to that
+ // mark is ignored. The first growth BEYOND it is the reply arriving,
+ // which is what following is for; the mark is then dropped so the rest
+ // of the turn streams normally.
+ const claimedHeight = claimedHeightRef.current;
+ if (claimedHeight !== null) {
+ if (viewport.scrollHeight <= claimedHeight) return;
+ claimedHeightRef.current = null;
+ }
// `instant` overrides the viewport's `scroll-smooth`: a smooth animation
// per token would lag permanently behind the stream.
viewport.scrollTo({ top: viewport.scrollHeight, behavior: 'instant' });
@@ -587,7 +649,7 @@ function useFollowBottom(
};
}, [contentRef, viewportRef]);
- return followRef;
+ return { followRef, claimScroll };
}
/**
@@ -598,7 +660,8 @@ function useFollowBottom(
const ThreadBottomFollower: FC<{
viewportRef: RefObject<HTMLDivElement | null>;
contentRef: RefObject<HTMLDivElement | null>;
-}> = ({ viewportRef, contentRef }) => {
+ claimScroll: () => void;
+}> = ({ viewportRef, contentRef, claimScroll }) => {
const latestMessage = useAuiState(s => s.thread.messages.at(-1));
useLayoutEffect(() => {
@@ -610,8 +673,26 @@ const ThreadBottomFollower: FC<{
return;
}
const userMessages = contentRef.current?.querySelectorAll<HTMLElement>('[data-role="user"]');
- userMessages?.item(userMessages.length - 1)?.scrollIntoView({ block: 'start' });
- }, [contentRef, latestMessage?.id, latestMessage?.role, viewportRef]);
+ // `behavior: 'instant'`, like the other two scrolls in this file, and for a
+ // second reason beyond overriding `scroll-smooth`: `claimScroll` below
+ // re-baselines from `viewport.scrollTop`, which is only correct if the move
+ // has already happened. A smooth alignment has NOT moved it by the time the
+ // next line runs, so the baseline would capture the pre-scroll position and
+ // the animation's own scroll events — a run of decreasing `scrollTop` —
+ // would read as the reader scrolling away, clearing the flag exactly when
+ // the reply starts. That failed intermittently rather than always, since a
+ // growth event landing between animation frames could re-arm it.
+ userMessages
+ ?.item(userMessages.length - 1)
+ ?.scrollIntoView({ block: 'start', behavior: 'instant' });
+ // This alignment scrolls UP whenever the reader was at the bottom — the new
+ // user message sits above the trailing `mb-14` and running-status slot, so
+ // bringing its top to the viewport top lowers `scrollTop`. To
+ // `useFollowBottom`'s listener that is indistinguishable from the reader
+ // scrolling away, and it would clear the follow flag at the exact moment
+ // the reply starts arriving. Re-arm: this scroll is ours, not theirs.
+ claimScroll();
+ }, [claimScroll, contentRef, latestMessage?.id, latestMessage?.role, viewportRef]);
return null;
};
diff --git a/app/test/playwright/specs/chat-harness-scroll-render.spec.ts b/app/test/playwright/specs/chat-harness-scroll-render.spec.ts
index 2bca44fd69..343b696917 100644
--- a/app/test/playwright/specs/chat-harness-scroll-render.spec.ts
+++ b/app/test/playwright/specs/chat-harness-scroll-render.spec.ts
@@ -141,6 +141,23 @@ test.describe('Chat Harness - Scroll Render', () => {
await expect(page.getByText(CANARY_BOLD)).toBeVisible({ timeout: 40_000 });
await expect(page.getByText(CANARY_CODE)).toBeVisible({ timeout: 20_000 });
+ // Assert the FIXTURE arrived, not just its last chunk.
+ //
+ // The canaries live in the markdown, which the mock streams AFTER the 120
+ // filler lines — so their presence looks like proof the whole reply landed.
+ // It is not. Measured on a failing run: `canary: true`, 2 messages, and a
+ // total `scrollHeight` of 960px against a 696px viewport. 120 lines cannot
+ // fit in 264px of overflow, so the filler had not streamed; the transcript
+ // was a different, barely-overflowing fixture and every scroll assertion
+ // below was measuring the wrong thing.
+ //
+ // Without this the run fails as "the transcript must settle at the bottom",
+ // which points at the scroll code and is the wrong place to look.
+ await expect(
+ page.getByText(FILLER_LINES[FILLER_LINES.length - 1], { exact: false }).last(),
+ 'the filler lines must stream before any scroll measurement — see note above'
+ ).toBeVisible({ timeout: 20_000 });
+
const tags = await page.evaluate(() => {
const column = document.querySelector(
'[data-slot="aui_thread-viewport"]'