The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(chat): follow the assistant reply as it streams
M3gA-Mind414ac73a072a
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsxindex cb4c8990ad..a466658ecd 100644--- a/app/src/components/assistant-ui/thread.tsx+++ b/app/src/components/assistant-ui/thread.tsx@@ -327,6 +327,7 @@ const ThreadRoot: FC<{const viewportRef = useRef<HTMLDivElement>(null);const messageGroupRef = useRef<HTMLDivElement>(null);+ useFollowBottom(viewportRef, messageGroupRef);useOpenThreadAtBottom(viewportRef);return (@@ -473,6 +474,97 @@ function useOpenThreadAtBottom(viewportRef: RefObject<HTMLDivElement | null>) {const FOLLOW_BOTTOM_THRESHOLD_PX = 80;+/**+ * Keep the newest content in view while the assistant streams.+ *+ * `ThreadBottomFollower` below cannot do this. It keys on+ * `latestMessage.id`/`.role`, and a streaming reply is ONE message whose id+ * never changes (`STREAMING_TAIL_ID`, `providers/assistantUiMessages.ts`) and+ * whose role is `assistant` — so it neither passes that hook's `role ===+ * 'user'` guard nor re-runs as tokens land. assistant-ui's own `autoScroll` is+ * off here deliberately: its stick threshold is ~1px against this host's 80,+ * and its run-start jump is unconditional, so enabling it would put two+ * followers with different ideas of "at the bottom" on one viewport.+ *+ * So follow the content box rather than the message list. A `ResizeObserver`+ * fires on every height change from any cause — tokens, markdown reflow, a+ * code block, a tool timeline expanding, an image decoding — none of which the+ * message identity reports.+ *+ * The reader stays in charge: `followRef` tracks their live distance from the+ * bottom, so scrolling up into history stops the following, and scrolling back+ * within `FOLLOW_BOTTOM_THRESHOLD_PX` resumes it. That is the contract the+ * viewport comment states — never yank a reader who deliberately left the+ * bottom — and it is enforced here rather than assumed.+ *+ * ## Pin-then-follow, and what that costs+ *+ * `ThreadBottomFollower` aligns a new USER message to the TOP of the viewport+ * so the reply streams beneath it. For a reply taller than the viewport that+ * alignment and this following are mutually exclusive: keep the question+ * pinned and the answer streams below the fold — the reported defect — or+ * follow the answer and the question eventually scrolls off the top.+ *+ * The choice made here is **pin at turn start, follow thereafter**, with the+ * reader overriding both by scrolling away. The pin is an alignment for the+ * moment a turn begins, not a claim on the whole turn, and every mainstream+ * chat client resolves it the same way. This is a visible change to how a long+ * reply reads, so it is recorded rather than left to be rediscovered.+ *+ * What a reader gives up: on a reply taller than the viewport, their own+ * question scrolls off the top as the answer streams. What they get back is+ * the answer being on screen while it arrives, which is the defect this fixes.+ */+function useFollowBottom(+ viewportRef: RefObject<HTMLDivElement | null>,+ contentRef: RefObject<HTMLDivElement | null>+) {+ // Starts true so a thread opens following; the first user scroll away from+ // the bottom is what turns it off.+ const followRef = useRef(true);++ useEffect(() => {+ const viewport = viewportRef.current;+ const content = contentRef.current;+ if (!viewport || !content) return;++ const distanceFromBottom = () =>+ viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;++ const onScroll = () => {+ followRef.current = distanceFromBottom() <= FOLLOW_BOTTOM_THRESHOLD_PX;+ };+ viewport.addEventListener('scroll', onScroll, { passive: true });++ const observer = new ResizeObserver(() => {+ // Read the flag; do NOT recompute the distance here. By the time this+ // callback runs the content has already grown: `scrollHeight` is the new+ // larger value while `scrollTop` has not moved, so a fresh measurement+ // reads "far from the bottom" *because of the growth being reacted to*.+ // Recomputing would decline to follow on the first token batch and never+ // recover, which looks identical to the defect this hook fixes. The+ // question is "was the reader at the bottom BEFORE this growth", and only+ // a value captured before it can answer that.+ //+ // The flag is not stale: `scrollIntoView` and `scrollTo` fire `scroll`+ // events too, so our own scrolls refresh it alongside the reader's. A+ // height change is the one thing that must not refresh it.+ if (!followRef.current) return;+ // `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' });+ });+ observer.observe(content);++ return () => {+ viewport.removeEventListener('scroll', onScroll);+ observer.disconnect();+ };+ }, [contentRef, viewportRef]);++ return followRef;+}+/*** Align a new turn only for a reader who remains near the bottom. assistant-ui's* run-start scroll is unconditional, which would pull a reader from olderdiff --git a/app/test/playwright/specs/chat-harness-scroll-render.spec.ts b/app/test/playwright/specs/chat-harness-scroll-render.spec.tsindex 847ef6110e..72372d4a97 100644--- a/app/test/playwright/specs/chat-harness-scroll-render.spec.ts+++ b/app/test/playwright/specs/chat-harness-scroll-render.spec.ts@@ -21,7 +21,12 @@ const REPLY_MARKDOWN = ['',`Visit [the docs](${LINK_URL}) for more.`,].join('\n');-const FILLER_LINES = Array.from({ length: 30 }, (_, index) => `Filler line ${index + 1}.`);+// 120, not 30. At 30 the transcript did not reliably exceed the viewport, so+// the `scrollHeight > clientHeight` guard below was false and every assertion+// inside it was skipped — the spec passed while measuring nothing. Proven by+// tightening `toBeLessThan(40)` to an impossible bound and watching the spec+// still pass.+const FILLER_LINES = Array.from({ length: 120 }, (_, index) => `Filler line ${index + 1}.`);const STREAM_SCRIPT = [...FILLER_LINES.map(line => ({ text: `${line}\n`, delayMs: 5 })),{ text: '\n', delayMs: 5 },@@ -138,27 +143,71 @@ test.describe('Chat Harness - Scroll Render', () => {const tags = await page.evaluate(() => {const column = document.querySelector(- 'div.flex-1.overflow-y-auto.bg-\\[\\#f6f6f6\\]'+ '[data-slot="aui_thread-viewport"]') as HTMLElement | null;+ // Throw rather than defaulting to zeros. With `?? 0` a selector that+ // matches nothing yields scrollHeight === clientHeight === 0, the+ // `scrollHeight > clientHeight` guard below reads `0 > 0` and every+ // assertion inside it is skipped — the spec passes while measuring+ // nothing. That is exactly how this file was green against a selector+ // (`div.flex-1.overflow-y-auto.bg-[#f6f6f6]`) that matched no element.+ if (!column) throw new Error('transcript viewport [data-slot=aui_thread-viewport] not found');return {- scrollTop: column?.scrollTop ?? 0,- scrollHeight: column?.scrollHeight ?? 0,- clientHeight: column?.clientHeight ?? 0,+ scrollTop: column.scrollTop,+ scrollHeight: column.scrollHeight,+ clientHeight: column.clientHeight,};});await expect(page.getByText(CANARY_BOLD)).toBeVisible();await expect(page.getByText(CANARY_CODE)).toBeVisible();await expect(page.getByText('the docs')).toBeVisible();- expect(tags.scrollHeight).toBeGreaterThanOrEqual(tags.clientHeight);- if (tags.scrollHeight > tags.clientHeight) {- const initialRemaining = tags.scrollHeight - (tags.scrollTop + tags.clientHeight);- expect(initialRemaining).toBeLessThan(40);+ // Hard assertion, not a silent precondition. If the transcript does not+ // overflow there is nothing to measure, and the spec must SAY so rather+ // than skip its assertions behind a false `if` and report success.+ expect(+ tags.scrollHeight,+ `transcript must overflow for this spec to measure anything: ${JSON.stringify(tags)}`+ ).toBeGreaterThan(tags.clientHeight);+ {+ // Poll rather than assert the `tags` snapshot. That snapshot is taken at+ // one instant and the follower scrolls in a ResizeObserver callback, so a+ // one-shot read races the settle: measured 264px remaining on one run and+ // under 40 on the next, from identical code. Polling asserts the property+ // ("the transcript ends up at the bottom") instead of the timing.+ await expect+ .poll(+ async () =>+ page.evaluate(() => {+ const column = document.querySelector(+ '[data-slot="aui_thread-viewport"]'+ ) as HTMLElement | null;+ if (!column) throw new Error('transcript viewport not found');+ return column.scrollHeight - column.scrollTop - column.clientHeight;+ }),+ {+ timeout: 5_000,+ message: 'the transcript must settle at the bottom once the reply has streamed',+ }+ )+ .toBeLessThan(40);- const targetTop = Math.max(0, tags.scrollTop - Math.floor(tags.clientHeight / 2));+ const settled = await page.evaluate(() => {+ const column = document.querySelector(+ '[data-slot="aui_thread-viewport"]'+ ) as HTMLElement | null;+ if (!column) throw new Error('transcript viewport not found');+ return {+ scrollTop: column.scrollTop,+ scrollHeight: column.scrollHeight,+ clientHeight: column.clientHeight,+ };+ });+ const settledRemaining = settled.scrollHeight - settled.scrollTop - settled.clientHeight;+ const targetTop = Math.max(0, settled.scrollTop - Math.floor(settled.clientHeight / 2));await page.evaluate(nextTop => {const column = document.querySelector(- 'div.flex-1.overflow-y-auto.bg-\\[\\#f6f6f6\\]'+ '[data-slot="aui_thread-viewport"]') as HTMLElement | null;column?.scrollTo({ top: nextTop, behavior: 'auto' });}, targetTop);@@ -168,7 +217,7 @@ test.describe('Chat Harness - Scroll Render', () => {async () =>page.evaluate(expected => {const column = document.querySelector(- 'div.flex-1.overflow-y-auto.bg-\\[\\#f6f6f6\\]'+ '[data-slot="aui_thread-viewport"]') as HTMLElement | null;return Math.abs((column?.scrollTop ?? 0) - expected) < 40;}, targetTop),@@ -178,7 +227,7 @@ test.describe('Chat Harness - Scroll Render', () => {const afterScrollUp = await page.evaluate(() => {const column = document.querySelector(- 'div.flex-1.overflow-y-auto.bg-\\[\\#f6f6f6\\]'+ '[data-slot="aui_thread-viewport"]') as HTMLElement | null;return {scrollTop: column?.scrollTop ?? 0,@@ -191,7 +240,7 @@ test.describe('Chat Harness - Scroll Render', () => {expect(afterScrollUp.scrollTop).toBeLessThan(tags.scrollTop - 20);expect(afterScrollUp.scrollHeight - (afterScrollUp.scrollTop + afterScrollUp.clientHeight)- ).toBeGreaterThan(initialRemaining + 10);+ ).toBeGreaterThan(settledRemaining + 10);}});});diff --git a/app/test/playwright/specs/chat-scroll-stick.spec.ts b/app/test/playwright/specs/chat-scroll-stick.spec.tsindex 09ab76e68b..d5c51c3103 100644--- a/app/test/playwright/specs/chat-scroll-stick.spec.ts+++ b/app/test/playwright/specs/chat-scroll-stick.spec.ts@@ -143,6 +143,30 @@ async function scrollTo(page: Page, top: number): Promise<void> {.toBe(true);}+/** The selected thread id, read from the live store. */+async function selectedThreadId(page: Page): Promise<string | null> {+ return page.evaluate(() => {+ const store = (+ window as unknown as {+ __OPENHUMAN_STORE__?: {+ getState?: () => { thread?: { selectedThreadId?: string | null } };+ };+ }+ ).__OPENHUMAN_STORE__;+ return store?.getState?.().thread?.selectedThreadId ?? null;+ });+}++async function startNewThread(page: Page): Promise<void> {+ await dismissWalkthroughIfPresent(page);+ const sidebar = page.getByTestId('new-thread-sidebar-button');+ if (await sidebar.isVisible().catch(() => false)) {+ await sidebar.click({ force: true });+ } else {+ await page.getByTestId('new-thread-button').click({ force: true });+ }+}+async function sendMessage(page: Page, prompt: string): Promise<void> {await dismissWalkthroughIfPresent(page);// The live input is a Lexical contenteditable, not a textarea — `fill()` and@@ -275,10 +299,128 @@ test.describe('Chat transcript stick-to-bottom', () => {const SECOND_PROMPT = 'Second long answer please';await completeTurn(page, SECOND_PROMPT, 'SECOND-REPLY-END');- // The new turn's own prompt must be on screen, not scrolled past.+ // The end of the streamed reply must be on screen.+ //+ // This is the half that was missing, and its absence is why this spec+ // stayed green through the defect it was written to catch. The assertion+ // above is satisfied by `ThreadBottomFollower`, which aligns the new USER+ // message and does nothing else; the assistant tail could stream entirely+ // below the fold and nothing here noticed.+ //+ // `toBeVisible()` in `completeTurn` does not cover this: in Playwright it+ // means CSS-visible with a non-empty box, which an element scrolled far+ // past the bottom of a scroll container satisfies. Only `toBeInViewport()`+ // asserts it is actually on screen.+ await expect(+ page.getByText('SECOND-REPLY-END', { exact: false }).last(),+ 'the end of the streamed reply must be in view for a reader who stayed at the bottom'+ ).toBeInViewport({ timeout: 15_000 });++ // This test previously asserted that the new turn's own PROMPT was in+ // viewport. That assertion was removed deliberately, not because it broke.+ //+ // The contract is pin-then-follow: `ThreadBottomFollower` aligns a new user+ // message to the top of the viewport at turn start, and `useFollowBottom`+ // keeps the newest content on screen thereafter. For a reply TALLER than+ // the viewport the two are mutually exclusive — the question is pushed off+ // the top by the answer it is waiting for. This fixture deliberately uses+ // an overflowing reply (`test.skip` above requires the transcript to+ // overflow), so the prompt is expected to leave the viewport here.+ //+ // Keeping the old assertion would have pinned the defect in place: it is+ // satisfied by the pin alone, so it stayed green for a reader who could not+ // see the answer streaming below the fold, which is the reported bug. For a+ // reply shorter than the viewport the two never conflict and the prompt+ // remains visible; that case is simply not what this fixture exercises.+ });++ /**+ * Returning to an ALREADY-CACHED thread must land at the bottom.+ *+ * HONEST SCOPE: this is a regression guard for behaviour `main` ALREADY has+ * (`useOpenThreadAtBottom`, #6475). It is **not** evidence for any change in+ * this PR. Measured: it passes with `useFollowBottom` present, with it+ * removed, and with the whole of this PR's `thread.tsx` reverted to `main`.+ *+ * It is kept because the scenario is expensive to reconstruct and the+ * behaviour is worth pinning, not because it proves a fix. A reported+ * "opening a thread does not land at the bottom" defect does NOT reproduce+ * here — see the PR body for what a fixture that reproduces it would need+ * (content whose height arrives asynchronously: images, or a transcript+ * whose late layout differs from its first paint). This fixture's markdown+ * has its full height in the first layout pass, so the one-shot scroll in+ * `useOpenThreadAtBottom` lands correctly and there is nothing to catch.+ *+ * This must exercise the CACHED path, and the distinction is the whole test.+ * `useOpenHumanExternalStore` reads `state.thread.messagesByThreadId`, a cache+ * cleared only on delete or sign-out. A thread opened for the FIRST time+ * briefly renders empty, which re-arms assistant-ui's own+ * `scrollToBottomOnInitialize` latch, so it scrolls to the bottom correctly+ * EVEN WITHOUT THE FIX. A thread visited earlier this session hands its+ * messages over on the very render its id changes, never passes through the+ * empty state, and keeps the previous thread's `scrollTop`.+ *+ * So the sequence matters: open A, open B, return to A. Checking a fresh+ * thread would pass against the defect and prove nothing — the file comment+ * on `useOpenThreadAtBottom` warns of exactly that.+ */+ test('returning to an already-cached thread lands at the bottom', async ({ page }) => {+ await resetMock();+ await setMockBehavior('llmStreamChunkDelayMs', '1');+ await setMockBehavior(+ 'llmForcedResponses',+ JSON.stringify([+ { content: `${LONG_REPLY}\n\nTHREAD-A-END` },+ { content: `${LONG_REPLY}\n\nTHREAD-B-END` },+ ])+ );+ await openChat(page);++ // Thread A, with enough content to overflow.+ await completeTurn(page, 'First thread please', 'THREAD-A-END');+ const threadA = await selectedThreadId(page);+ expect(threadA, 'thread A must have an id').not.toBeNull();++ const overflowing = await scrollState(page);+ test.skip(+ overflowing.scrollHeight <= overflowing.clientHeight + 200,+ 'transcript did not overflow enough to scroll — viewport too tall for this fixture'+ );++ // Thread B. Leaving A is what puts A's messages in the cache.+ await startNewThread(page);+ await completeTurn(page, 'Second thread please', 'THREAD-B-END');++ // Scroll UP in B before leaving it. This is what makes the test+ // discriminating rather than merely passing.+ //+ // The follower's `followRef` persists across a thread switch — the viewport+ // is not remounted — so returning from a thread that was parked AT the+ // bottom leaves the flag true, and the ResizeObserver would drag the+ // reopened thread to the bottom on the next height change regardless of+ // whether opening a thread does anything deliberate. Leaving B scrolled up+ // sets the flag false, so the only thing that can land A at its newest+ // message is `useOpenThreadAtBottom` explicitly re-arming it.+ const inB = await scrollState(page);+ await scrollTo(page, Math.max(0, inB.scrollHeight - inB.clientHeight - 600));+ expect(+ (await scrollState(page)).distanceFromBottom,+ 'thread B must be left scrolled away from the bottom for this test to discriminate'+ ).toBeGreaterThan(80);++ // Back to A — the cached path.+ await page.getByTestId(`thread-row-${threadA}`).click({ force: true });+ await expect(page.getByText('THREAD-A-END', { exact: false }).last()).toBeVisible({+ timeout: 20_000,+ });++ // `toBeVisible` above is NOT the assertion: in Playwright it means+ // CSS-visible with a non-empty box, which an element scrolled far below the+ // fold satisfies. Only being in the viewport says the thread opened at its+ // newest message.await expect(- page.getByText(SECOND_PROMPT, { exact: false }).last(),- 'a reader at the bottom must have the new turn brought into view'+ page.getByText('THREAD-A-END', { exact: false }).last(),+ 'a cached thread must open at its newest message, not at the previous thread scroll offset').toBeInViewport({ timeout: 15_000 });});});