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): correct scroll-to-bottom behavior on new window
Steven Enamakelf8a0f3ff2a86
diff --git a/app/src/components/chat/ChatNewWindowHero.test.tsx b/app/src/components/chat/ChatNewWindowHero.test.tsxdeleted file mode 100644index 4b7139a21d..0000000000--- a/app/src/components/chat/ChatNewWindowHero.test.tsx+++ /dev/null@@ -1,52 +0,0 @@-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';--import ChatNewWindowHero from './ChatNewWindowHero';--vi.mock('../../hooks/useUser', () => ({ useUser: () => ({ user: { firstName: 'Ada' } }) }));--const mockUseUsageState = vi.hoisted(() =>- vi.fn(() => ({ shouldShowBudgetCompletedMessage: false }))-);-vi.mock('../../hooks/useUsageState', () => ({ useUsageState: mockUseUsageState }));--vi.mock('../../services/api/openrouterFreeModels', () => ({ applyOpenRouterFreeModels: vi.fn() }));--const blockingStateMock = vi.hoisted(() => ({ current: 'ok' as string }));-vi.mock('../../store/connectivitySelectors', () => ({- selectBlockingState: () => blockingStateMock.current,-}));-vi.mock('../../store/hooks', () => ({- useAppSelector: (selector: (s: unknown) => unknown) => selector(undefined),-}));--const restartCoreProcessMock = vi.fn<() => Promise<void>>(() => Promise.resolve());-vi.mock('../../services/coreProcessControl', () => ({- restartCoreProcess: () => restartCoreProcessMock(),-}));--describe('ChatNewWindowHero', () => {- it('renders the greeting card without the core-recovery button by default', () => {- blockingStateMock.current = 'ok';- const { container } = render(<ChatNewWindowHero />);- expect(container.querySelector('[data-walkthrough="home-card"]')).toBeTruthy();- expect(screen.queryByRole('button', { name: /restart/i })).toBeNull();- });-- it('shows a restart-core button when the core is unreachable, and invokes it', async () => {- blockingStateMock.current = 'core-unreachable';- render(<ChatNewWindowHero />);- const restart = screen.getByRole('button', { name: /restart/i });- fireEvent.click(restart);- await waitFor(() => expect(restartCoreProcessMock).toHaveBeenCalled());- });-- it('renders the prompt heading that used to live in the composer placeholder', () => {- blockingStateMock.current = 'ok';- render(<ChatNewWindowHero />);- // Real heading now, not hint text inside the textarea. The e2e- // `textExists('How can I help you today?')` check in- // conversations-web-channel-flow depends on it being on-screen text.- expect(screen.getByRole('heading', { name: 'How can I help you today?' })).toBeInTheDocument();- });-});diff --git a/app/src/components/chat/ChatNewWindowHero.tsx b/app/src/components/chat/ChatNewWindowHero.tsxdeleted file mode 100644index 2f18d3b10d..0000000000--- a/app/src/components/chat/ChatNewWindowHero.tsx+++ /dev/null@@ -1,159 +0,0 @@-import { useEffect, useMemo, useState } from 'react';--import { useUser } from '../../hooks/useUser';-import { useT } from '../../lib/i18n/I18nContext';-import { restartCoreProcess } from '../../services/coreProcessControl';-import { selectBlockingState } from '../../store/connectivitySelectors';-import { useAppSelector } from '../../store/hooks';-import { resolveUserName } from '../../utils/userName';-import { DiscordBanner, PromotionalCreditsBanner } from '../home/HomeBanners';-import { Button } from '../ui';--/**- * Hero shown above the composer in the chat "new window" (empty thread) state —- * the merged Home surface. Mirrors the former Home card (greeting, connection- * status, version + light/dark toggle, banners), but drops the "Ask Assistant"- * CTA: the composer directly below is the call to action now. The- * core-unreachable recovery button is preserved since the composer is disabled- * while the core is down.- */-export default function ChatNewWindowHero() {- const { t } = useT();- const { user } = useUser();-- const userName = resolveUserName(user).split(' ')[0];- const promoCredits = user?.usage?.promotionBalanceUsd ?? 0;- const isFreeTier =- user?.subscription?.plan === 'FREE' || !user?.subscription?.hasActiveSubscription;- const showPromoBanner = isFreeTier && promoCredits > 0.01;-- const blocking = useAppSelector(selectBlockingState);-- const [isRestartingCore, setIsRestartingCore] = useState(false);- const [restartError, setRestartError] = useState<string | null>(null);-- const welcomeVariants = useMemo(- () => [- t('chat.newWindowWelcome1').replace('{name}', userName),- t('chat.newWindowWelcome2').replace('{name}', userName),- t('chat.newWindowWelcome3').replace('{name}', userName),- ],- [t, userName]- );- const [welcomeVariantIndex, setWelcomeVariantIndex] = useState(0);- const [typedWelcome, setTypedWelcome] = useState('');- const [isDeletingWelcome, setIsDeletingWelcome] = useState(false);-- const statusCopy = {- ok: t('home.statusOk'),- 'backend-only': t('home.statusBackendOnly'),- 'hosted-degraded': t('home.statusHostedDegraded'),- 'hosted-stopped': t('home.statusHostedStopped'),- 'core-unreachable': t('home.statusCoreUnreachable'),- 'internet-offline': t('home.statusInternetOffline'),- }[blocking];-- const handleRestartCore = async () => {- setIsRestartingCore(true);- setRestartError(null);- try {- await restartCoreProcess();- } catch (err) {- setRestartError(err instanceof Error ? err.message : String(err));- } finally {- setIsRestartingCore(false);- }- };-- // Typewriter cycle — identical cadence to the former Home greeting.- useEffect(() => {- const activeVariant = welcomeVariants[welcomeVariantIndex] ?? '';- const isFullyTyped = typedWelcome === activeVariant;- const isFullyDeleted = typedWelcome.length === 0;-- const delay = isDeletingWelcome- ? 36- : isFullyTyped- ? 1400- : typedWelcome.length === 0- ? 250- : 55;-- const timeoutId = window.setTimeout(() => {- if (!isDeletingWelcome) {- if (isFullyTyped) {- setIsDeletingWelcome(true);- return;- }- setTypedWelcome(activeVariant.slice(0, typedWelcome.length + 1));- return;- }- if (!isFullyDeleted) {- setTypedWelcome(activeVariant.slice(0, typedWelcome.length - 1));- return;- }- setIsDeletingWelcome(false);- setWelcomeVariantIndex(current => (current + 1) % welcomeVariants.length);- }, delay);-- return () => window.clearTimeout(timeoutId);- }, [isDeletingWelcome, typedWelcome, welcomeVariantIndex, welcomeVariants]);-- return (- <div className="mx-auto flex h-full w-full max-w-md flex-col justify-center py-4">- {showPromoBanner && <PromotionalCreditsBanner promoCredits={promoCredits} />}-- {/* Main card — sizes to its content. The full height lives on the- container (this column is h-full and centers the card), so the- composer stays pinned at the bottom of the surface. ~80% tint over- the app background. */}- <div- data-walkthrough="home-card"- // `surface-muted`, not `surface/80`: the translucent fill only read as a- // card while the chat page painted a darker tint beneath it. The page is- // the card surface now, so surface/80 over surface would flatten to the- // same colour and leave only the border. This is the same lift token the- // message bubbles use.- className="animate-fade-up rounded-2xl border border-line/80 bg-surface-muted p-6 shadow-soft dark:border-line/80">- {/* Animated greeting */}- <h1 className="min-h-14 text-2xl text-center font-bold text-content">- {typedWelcome}- <span aria-hidden="true" className="ml-0.5 inline-block animate-pulse text-primary-500">- |- </span>- </h1>-- {/* Description — copy mirrors the active blocking state (incl. the- "device connected" get-started line in the normal case). */}- <p className="text-center text-sm leading-relaxed text-content-muted">{statusCopy}</p>-- {/* Recovery: only when the local core is the broken link. */}- {blocking === 'core-unreachable' && (- <div className="mt-4">- <Button- size="lg"- onClick={handleRestartCore}- disabled={isRestartingCore}- className="w-full rounded-xl bg-amber-500 text-content-inverted hover:bg-amber-600">- {isRestartingCore ? t('home.restartingCore') : t('home.restartCore')}- </Button>- {restartError && (- <p className="mt-2 text-center text-xs text-coral-500">{restartError}</p>- )}- </div>- )}- </div>-- {/* Prompt heading — sits directly above the composer, which is the call- to action. This is the string the composer placeholder used to carry- (`chat.typeMessage`); the placeholder is now the plain- "Send a message" affordance, so the question moved here where it can- be a real heading rather than hint text inside an input. */}- <h2 className="mt-6 text-center text-lg font-semibold text-content">- {t('chat.newWindowPrompt')}- </h2>-- <DiscordBanner />- </div>- );-}diff --git a/app/src/features/share/ShareMessageButton.test.tsx b/app/src/features/share/ShareMessageButton.test.tsxdeleted file mode 100644index 3725865d85..0000000000--- a/app/src/features/share/ShareMessageButton.test.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { render, screen } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { describe, expect, test, vi } from 'vitest';--import { ShareMessageButton } from './ShareMessageButton';--vi.mock('./ShareCardModal', () => ({- ShareCardModal: ({ onClose }: { onClose: () => void }) => (- <div data-testid="share-modal">- <button onClick={onClose}>close</button>- </div>- ),-}));--describe('ShareMessageButton', () => {- test('renders nothing when there is no shareable content', () => {- const { container } = render(<ShareMessageButton content=" " agentName="Tiny" />);- expect(container.firstChild).toBeNull();- });-- test('renders a share trigger for agent content', () => {- render(<ShareMessageButton content="Did the thing" agentName="Tiny" />);- expect(screen.getByTestId('chat-message-share')).toBeInTheDocument();- expect(screen.queryByTestId('share-modal')).not.toBeInTheDocument();- });-- test('opens and closes the share modal', async () => {- const user = userEvent.setup();- render(<ShareMessageButton content="Did the thing" agentName="Tiny" threadId="t1" />);-- await user.click(screen.getByTestId('chat-message-share'));- expect(screen.getByTestId('share-modal')).toBeInTheDocument();-- await user.click(screen.getByText('close'));- expect(screen.queryByTestId('share-modal')).not.toBeInTheDocument();- });-});diff --git a/app/src/features/share/ShareMessageButton.tsx b/app/src/features/share/ShareMessageButton.tsxdeleted file mode 100644index 6dafdd3ab6..0000000000--- a/app/src/features/share/ShareMessageButton.tsx+++ /dev/null@@ -1,68 +0,0 @@-import { useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import { ShareCardModal } from './ShareCardModal';--interface ShareMessageButtonProps {- /** Plain-text agent output to turn into a share card. */- content: string;- /** Display name of the agent/profile that produced the output. */- agentName: string;- /** Optional thread id, forwarded to inference for log grouping. */- threadId?: string;- /** Extra classes for positioning within the message row. */- className?: string;-}--/**- * Hover-revealed "Share" affordance rendered under a completed agent message- * (issue #5006). Opens `ShareCardModal`. Self-contained so the wiring into the- * large `Conversations.tsx` message list stays a one-liner. Renders nothing when- * there is no shareable text.- */-export function ShareMessageButton({- content,- agentName,- threadId,- className = '',-}: ShareMessageButtonProps) {- const { t } = useT();- const [open, setOpen] = useState(false);-- if (!content.trim()) return null;-- return (- <>- <button- type="button"- data-analytics-id="chat-message-share"- data-testid="chat-message-share"- onClick={() => setOpen(true)}- title={t('share.button')}- aria-label={t('share.button')}- className={`p-1 rounded-md opacity-0 group-hover/msg:opacity-100 hover:bg-surface-hover dark:bg-surface-muted dark:hover:bg-surface-muted text-content-faint hover:text-content-secondary transition-all ${className}`}>- <svg- className="w-3.5 h-3.5"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- aria-hidden="true">- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M8.7 10.7l6.6-3.4M8.7 13.3l6.6 3.4M18 8a3 3 0 100-6 3 3 0 000 6zM6 15a3 3 0 100-6 3 3 0 000 6zm12 7a3 3 0 100-6 3 3 0 000 6z"- />- </svg>- </button>- {open ? (- <ShareCardModal- content={content}- agentName={agentName}- threadId={threadId}- onClose={() => setOpen(false)}- />- ) : null}- </>- );-}diff --git a/app/src/hooks/useStickToBottom.test.ts b/app/src/hooks/useStickToBottom.test.tsdeleted file mode 100644index db105ae017..0000000000--- a/app/src/hooks/useStickToBottom.test.ts+++ /dev/null@@ -1,153 +0,0 @@-import { fireEvent, render } from '@testing-library/react';-import { createElement } from 'react';-import { describe, expect, it } from 'vitest';--import { isNearBottom, useStickToBottom } from './useStickToBottom';--/**- * jsdom performs no real layout, so `scrollHeight`/`clientHeight`/`scrollTop`- * are inert (always 0) unless we define them ourselves. This gives the- * container concrete, mutable scroll metrics so `isNearBottom` and- * `snapToBottom` (inside the hook) behave exactly as they would in a real- * browser for the geometry each test sets up.- */-function mockScrollMetrics(- el: HTMLElement,- metrics: { scrollTop: number; scrollHeight: number; clientHeight: number }-) {- Object.defineProperty(el, 'scrollHeight', { configurable: true, value: metrics.scrollHeight });- Object.defineProperty(el, 'clientHeight', { configurable: true, value: metrics.clientHeight });- Object.defineProperty(el, 'scrollTop', {- configurable: true,- writable: true,- value: metrics.scrollTop,- });-}--interface HarnessProps {- messages: unknown[];- threadKey: string | null;- resetKey: string;-}--/** Minimal host component — the hook never touches the DOM directly, callers- * wire `containerRef` onto their own scroll container. */-function Harness({ messages, threadKey, resetKey }: HarnessProps) {- const { containerRef } = useStickToBottom(messages, threadKey, resetKey);- return createElement(- 'div',- { ref: containerRef, 'data-testid': 'scroll-container' },- messages.map((m, i) => createElement('div', { key: i }, String(m)))- );-}--describe('useStickToBottom', () => {- it('is a pure, independently-testable is-at-bottom check', () => {- // Exactly at the default 80px threshold: still "at bottom".- expect(- isNearBottom({ scrollHeight: 180, scrollTop: 100, clientHeight: 80 } as HTMLElement)- ).toBe(true);- // One pixel past the threshold (distance = 181 - 20 - 80 = 81): no- // longer "at bottom".- expect(- isNearBottom({ scrollHeight: 181, scrollTop: 20, clientHeight: 80 } as HTMLElement)- ).toBe(false);- // A custom threshold is honoured.- expect(- isNearBottom({ scrollHeight: 300, scrollTop: 100, clientHeight: 80 } as HTMLElement, 200)- ).toBe(true);- });-- it('auto-scrolls to the newest content when the user is already pinned to the bottom', () => {- const { getByTestId, rerender } = render(- createElement(Harness, { messages: ['first'], threadKey: 't1', resetKey: 'k' })- );- const container = getByTestId('scroll-container');-- // Establish "at the bottom" after the initial (always-snaps) mount.- mockScrollMetrics(container, { scrollTop: 50, scrollHeight: 100, clientHeight: 50 });- rerender(createElement(Harness, { messages: ['first'], threadKey: 't1', resetKey: 'k' }));-- // A new message arrives — content grows (scrollHeight increases) while- // the user never moved away from the bottom. Because `stickingRef` is- // still true, the layout effect must snap to the new bottom.- mockScrollMetrics(container, { scrollTop: 50, scrollHeight: 300, clientHeight: 50 });- rerender(- createElement(Harness, { messages: ['first', 'second'], threadKey: 't1', resetKey: 'k' })- );-- expect(container.scrollTop).toBe(300);- });-- it('does NOT auto-scroll (respects the user reading history) once they scroll away from the bottom', () => {- const { getByTestId, rerender } = render(- createElement(Harness, { messages: ['first'], threadKey: 't1', resetKey: 'k' })- );- const container = getByTestId('scroll-container');-- mockScrollMetrics(container, { scrollTop: 50, scrollHeight: 100, clientHeight: 50 });- rerender(createElement(Harness, { messages: ['first'], threadKey: 't1', resetKey: 'k' }));-- // The user scrolls up, well past the stick threshold (400 - 0 - 50 =- // 350px from the bottom) — the `scroll` listener must disengage sticking.- mockScrollMetrics(container, { scrollTop: 0, scrollHeight: 400, clientHeight: 50 });- fireEvent.scroll(container);-- // A new message arrives (content grows further) while the user is still- // reading up top. This is exactly the bug being fixed: the old- // unconditional `scrollTo` effect would yank the user back down here —- // the container must stay exactly where the reader left it.- mockScrollMetrics(container, { scrollTop: 0, scrollHeight: 700, clientHeight: 50 });- rerender(- createElement(Harness, { messages: ['first', 'second'], threadKey: 't1', resetKey: 'k' })- );-- expect(container.scrollTop).toBe(0);- });-- it('re-engages sticking once the user manually scrolls back to the bottom', () => {- const { getByTestId, rerender } = render(- createElement(Harness, { messages: ['first'], threadKey: 't1', resetKey: 'k' })- );- const container = getByTestId('scroll-container');-- mockScrollMetrics(container, { scrollTop: 50, scrollHeight: 100, clientHeight: 50 });- rerender(createElement(Harness, { messages: ['first'], threadKey: 't1', resetKey: 'k' }));-- // Scroll away (350px from bottom — well past the threshold).- mockScrollMetrics(container, { scrollTop: 0, scrollHeight: 400, clientHeight: 50 });- fireEvent.scroll(container);-- // Scroll back within the threshold (400 - 350 - 50 = 0px from bottom).- mockScrollMetrics(container, { scrollTop: 350, scrollHeight: 400, clientHeight: 50 });- fireEvent.scroll(container);-- // A new message now DOES pull the view down again.- mockScrollMetrics(container, { scrollTop: 350, scrollHeight: 600, clientHeight: 50 });- rerender(- createElement(Harness, { messages: ['first', 'second'], threadKey: 't1', resetKey: 'k' })- );-- expect(container.scrollTop).toBe(600);- });-- it('always snaps on a thread change, even mid-read (a fresh conversation should open at the bottom)', () => {- const { getByTestId, rerender } = render(- createElement(Harness, { messages: ['a1'], threadKey: 'thread-a', resetKey: 'k' })- );- const container = getByTestId('scroll-container');- mockScrollMetrics(container, { scrollTop: 50, scrollHeight: 100, clientHeight: 50 });- rerender(createElement(Harness, { messages: ['a1'], threadKey: 'thread-a', resetKey: 'k' }));-- // Scroll away on thread A.- mockScrollMetrics(container, { scrollTop: 0, scrollHeight: 400, clientHeight: 50 });- fireEvent.scroll(container);-- // Switch to a different thread entirely — must snap regardless of the- // stale `stickingRef` from thread A.- mockScrollMetrics(container, { scrollTop: 0, scrollHeight: 250, clientHeight: 50 });- rerender(createElement(Harness, { messages: ['b1'], threadKey: 'thread-b', resetKey: 'k' }));-- expect(container.scrollTop).toBe(250);- });-});diff --git a/app/src/hooks/useStickToBottom.ts b/app/src/hooks/useStickToBottom.tsdeleted file mode 100644index 59280d1e7f..0000000000--- a/app/src/hooks/useStickToBottom.ts+++ /dev/null@@ -1,171 +0,0 @@-import createDebug from 'debug';-import { useEffect, useLayoutEffect, useRef } from 'react';--/**- * Keep a scroll container pinned to the bottom as messages arrive.- *- * Three observers cooperate:- * 1. Layout-effect on `messages` / `threadKey` / `resetKey` — handles thread- * swaps and the first paint, instantly snapping to the latest message.- * 2. `scroll` listener — toggles `stickingRef` based on the user's distance- * from the bottom so manual scroll-up disengages the auto-snap.- * 3. ResizeObserver on the container *and its children*, plus a- * MutationObserver on the container's `childList` that re-binds the- * ResizeObserver whenever the subtree is swapped. This keeps streaming- * agent replies in view: each token chunk grows the content height,- * the resize observer fires, and we snap to the new bottom before paint.- *- * If the user manually scrolls up past the threshold we stop sticking, so they- * can read history without being yanked down. Scrolling back to the bottom- * re-engages stickiness on the next render.- *- * Root-cause note (copilot "chat gets stuck" bug): a naive `useEffect` that- * unconditionally calls `scrollTo(bottom)` on every dependency change (new- * message, streamed token, tool-timeline entry, …) fights a user who has- * scrolled up to read — it snaps them back down mid-read, which reads as the- * scroll container "locking up". This hook is the fix for that pattern:- * auto-scroll only fires while `stickingRef` is true (i.e. the user was- * already at/near the bottom), so scrolling up always disengages it.- */--const log = createDebug('app:hooks:stick-to-bottom');--const STICK_THRESHOLD_PX = 80;--/** Pure, independently-testable "is this container at/near the bottom?" check. */-export function isNearBottom(el: HTMLElement, thresholdPx: number = STICK_THRESHOLD_PX): boolean {- return el.scrollHeight - el.scrollTop - el.clientHeight <= thresholdPx;-}--function snapToBottom(el: HTMLElement) {- el.scrollTop = el.scrollHeight;-}--export function useStickToBottom(- messages: readonly unknown[],- threadKey: string | null | undefined,- resetKey: string-) {- const containerRef = useRef<HTMLDivElement>(null);- const endRef = useRef<HTMLDivElement>(null);- const didInitialScrollRef = useRef(false);- const lastScrolledThreadRef = useRef<string | null>(null);- const lastResetKeyRef = useRef(resetKey);- // Tracks whether we should keep auto-scrolling. Flips to false when the user- // scrolls up away from the bottom; flips back when they return.- const stickingRef = useRef(true);- // Mirrors `threadKey` for the mount-only resize-observer effect's log lines- // below — kept current every render so the logs stay accurate even though- // that effect itself intentionally doesn't re-run on a thread change (the- // MutationObserver already re-binds the ResizeObserver on subtree swaps).- const threadKeyRef = useRef(threadKey);- threadKeyRef.current = threadKey;-- // ── Snap on message / thread / route changes ─────────────────────────────- useLayoutEffect(() => {- if (lastResetKeyRef.current !== resetKey) {- didInitialScrollRef.current = false;- lastResetKeyRef.current = resetKey;- }- // Record the active thread on every render (including empty ones) so- // the A → empty B → A navigation pattern is recognised as a thread- // change when A's messages re-arrive. Normalize `undefined` to `null`- // on BOTH sides of the comparison below — comparing the normalized- // previous value against a raw `threadKey` that happens to be- // `undefined` (rather than `null`) would make `threadChanged` true on- // every single run (`null !== undefined`), forcing an unwanted snap on- // every re-render for any caller whose "no thread yet" state is- // `undefined` instead of `null`. The param type explicitly allows- // `undefined`, so this normalization has to be symmetric.- const previousThread = lastScrolledThreadRef.current;- const normalizedThreadKey = threadKey ?? null;- lastScrolledThreadRef.current = normalizedThreadKey;- if (messages.length === 0) return;- const container = containerRef.current;- if (!container) return;-- const threadChanged = previousThread !== normalizedThreadKey;- const firstScroll = !didInitialScrollRef.current;- if (firstScroll || threadChanged || stickingRef.current) {- log(- 'layout-effect: snap fired (firstScroll=%s threadChanged=%s sticking=%s) count=%d thread=%s',- firstScroll,- threadChanged,- stickingRef.current,- messages.length,- normalizedThreadKey ?? 'null'- );- snapToBottom(container);- stickingRef.current = true;- } else {- log(- 'layout-effect: snap skipped (user scrolled up) count=%d thread=%s',- messages.length,- normalizedThreadKey ?? 'null'- );- }- didInitialScrollRef.current = true;- }, [messages, threadKey, resetKey]);-- // ── Track manual scroll → toggle stickingRef ─────────────────────────────- useEffect(() => {- const container = containerRef.current;- if (!container) return;- const onScroll = () => {- const atBottom = isNearBottom(container);- if (atBottom !== stickingRef.current) {- log('scroll: sticking %s -> %s (isNearBottom=%s)', stickingRef.current, atBottom, atBottom);- }- stickingRef.current = atBottom;- };- container.addEventListener('scroll', onScroll, { passive: true });- return () => container.removeEventListener('scroll', onScroll);- }, []);-- // ── Pin to bottom while content grows (streaming chunks) ─────────────────- //- // The ResizeObserver only fires for elements it's currently observing, so- // when the container's subtree gets swapped (e.g. switching from the- // welcome loader to the message list, or from one thread to another),- // we have to re-observe the new children. A MutationObserver on- // `childList` does that automatically.- useEffect(() => {- const container = containerRef.current;- if (!container) return;-- const resizeObserver = new ResizeObserver(() => {- if (stickingRef.current) {- log('resize-observer: snap fired (sticking) thread=%s', threadKeyRef.current ?? 'null');- snapToBottom(container);- } else {- log(- 'resize-observer: snap skipped (user scrolled up) thread=%s',- threadKeyRef.current ?? 'null'- );- }- });-- const observeAllChildren = () => {- // Disconnect first so we don't end up holding stale child refs after- // a subtree swap; then re-attach to the container and every direct- // child currently mounted.- resizeObserver.disconnect();- resizeObserver.observe(container);- for (let child = container.firstElementChild; child; child = child.nextElementSibling) {- resizeObserver.observe(child);- }- };-- observeAllChildren();-- const mutationObserver = new MutationObserver(() => observeAllChildren());- mutationObserver.observe(container, { childList: true });-- return () => {- resizeObserver.disconnect();- mutationObserver.disconnect();- };- }, []);-- return { containerRef, endRef };-}