Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
📜 style: Scroll the Sidebar as One Surface (#15914)
Marco Berettad8c953be30c8
diff --git a/client/src/components/Conversations/Conversations.tsx b/client/src/components/Conversations/Conversations.tsxindex 82e1254a8b..f8fc368a5f 100644--- a/client/src/components/Conversations/Conversations.tsx+++ b/client/src/components/Conversations/Conversations.tsx@@ -24,7 +24,7 @@ import {useEffectiveProjectId,useUnpinDroppedConversation,} from './dnd';-import { useLocalize, TranslationKeys, useElementSize } from '~/hooks';+import { useLocalize, TranslationKeys, useElementSize, useOuterScrollWindow } from '~/hooks';import { groupConversations, cn } from '~/utils';import { useActiveJobs } from '~/data-provider';import Convo from './Convo';@@ -58,6 +58,12 @@ interface ConversationsProps {isError?: boolean;/** Re-run the conversations request from the error state. */onRetry?: () => void;+ /** The sidebar's single scroll viewport: the list is windowed by it rather than+ * scrolling on its own, so the sections above it scroll with the chats. */+ scrollViewport: HTMLElement | null;+ /** Wrapper around everything inside that viewport, whose height changes when a+ * section above the list expands or collapses. */+ scrollContent: HTMLElement | null;}interface MeasuredRowProps {@@ -187,6 +193,8 @@ const Conversations: FC<ConversationsProps> = ({hasNextPage = false,isError = false,onRetry,+ scrollViewport,+ scrollContent,}) => {const localize = useLocalize();const search = useRecoilValue(store.search);@@ -232,11 +240,25 @@ const Conversations: FC<ConversationsProps> = ({});dropRef(chatsRegionRef);const convoHeight = isSmallScreen ? 44 : 34;+ const { ref: listContainerRef, width: listWidth } = useElementSize<HTMLDivElement>();+ /** The list does not scroll: the sidebar's one scroll container does, and the+ * list virtualizes against the slice of it the rows currently occupy. */const {- ref: listContainerRef,- width: listWidth,- height: listHeight,- } = useElementSize<HTMLDivElement>();+ ref: listWindowRef,+ height: windowHeight,+ scrollTop: windowScrollTop,+ isOnScreen: isListOnScreen,+ } = useOuterScrollWindow(scrollViewport, scrollContent);++ /** One element is both the width source and the window anchor; a stable+ * callback keeps React from detaching and reattaching it every render. */+ const setListNode = useCallback(+ (node: HTMLDivElement | null) => {+ listContainerRef(node);+ listWindowRef(node);+ },+ [listContainerRef, listWindowRef],+ );// Fetch active job IDs for showing generation indicatorsconst { data: activeJobsData } = useActiveJobs();@@ -440,11 +462,26 @@ const Conversations: FC<ConversationsProps> = ({const handleRowsRendered = useCallback(({ stopIndex }: { stopIndex: number }) => {+ /** Reaching the end of what is rendered only means the reader is near the+ * end of the list when the reader can see it. A list still below the+ * fold renders its first row to keep a height, and on a page whose chats+ * are nearly all pinned that row is already within the threshold — which+ * would spend another request on chats nobody has looked at. The list+ * fills the moment it comes into view instead; a page holding no chats+ * at all is drained by the separate all-pin effect above.+ *+ * Asked here rather than read from the last frame: a commit that swaps+ * what the sidebar holds — leaving a search restores the sections and+ * the unfiltered page together — reports its rows before any observer+ * has seen the new layout. */+ if (!isListOnScreen()) {+ return;+ }if (stopIndex >= flattenedItems.length - 8) {throttledLoadMore();}},- [flattenedItems.length, throttledLoadMore],+ [flattenedItems.length, throttledLoadMore, isListOnScreen],);const isListError =isChatsExpanded &&@@ -477,11 +514,13 @@ const Conversations: FC<ConversationsProps> = ({}let body: ReactNode = (- <div ref={listContainerRef} className="min-h-0 flex-1 overflow-hidden">+ <div ref={setListNode} className="flex-1"><Listref={containerRef}+ autoHeightwidth={listWidth}- height={listHeight}+ height={windowHeight}+ scrollTop={windowScrollTop}deferredMeasurementCache={cache}rowCount={flattenedItems.length}rowHeight={getRowHeight}@@ -546,7 +585,7 @@ const Conversations: FC<ConversationsProps> = ({return (<divref={chatsRegionRef}- className="relative flex h-full min-h-0 flex-col pb-2 text-sm text-text-primary"+ className="relative flex flex-1 flex-col pb-2 text-sm text-text-primary"><div className="px-3"><ChatsHeaderdiff --git a/client/src/components/Conversations/PinnedSection.tsx b/client/src/components/Conversations/PinnedSection.tsxindex 4fb478316e..0fb624dd64 100644--- a/client/src/components/Conversations/PinnedSection.tsx+++ b/client/src/components/Conversations/PinnedSection.tsx@@ -736,10 +736,8 @@ const PinnedSection = ({</div><Collapse open={isExpanded}>- {/* Projects above already claims up to 42vh; matching it here starved the- flex-growing Chats region on short viewports, so this keeps the- pre-existing budget. */}- <div className="scrollbar-gutter-stable max-h-[30vh] overflow-y-auto pt-0.5">+ {/* No scroll pane of its own: the sidebar scrolls as one surface. */}+ <div className="pt-0.5">{displayEntries.length === 0 && draggingConversation && (<divclassName={cn(diff --git a/client/src/components/Conversations/ProjectsSection.tsx b/client/src/components/Conversations/ProjectsSection.tsxindex 04f5de9846..edc9590394 100644--- a/client/src/components/Conversations/ProjectsSection.tsx+++ b/client/src/components/Conversations/ProjectsSection.tsx@@ -515,9 +515,8 @@ const ProjectsSection = ({ toggleNav, isAuthenticated }: ProjectsSectionProps) =</div><Collapse open={isExpanded}>- <div className="scrollbar-gutter-stable max-h-[42vh] overflow-y-auto pt-0.5">- {renderProjectsBody()}- </div>+ {/* No scroll pane of its own: the sidebar scrolls as one surface. */}+ <div className="pt-0.5">{renderProjectsBody()}</div></Collapse><ProjectCreateDialogdiff --git a/client/src/components/Conversations/__tests__/Conversations.test.tsx b/client/src/components/Conversations/__tests__/Conversations.test.tsxindex d81e79fb73..fe196f84d2 100644--- a/client/src/components/Conversations/__tests__/Conversations.test.tsx+++ b/client/src/components/Conversations/__tests__/Conversations.test.tsx@@ -62,6 +62,12 @@ jest.mock('~/store', () => {jest.mock('~/hooks', () => ({useLocalize: () => (key: string) => key,useElementSize: () => ({ ref: jest.fn(), width: 300, height: 600 }),+ useOuterScrollWindow: () => ({+ ref: jest.fn(),+ height: 600,+ scrollTop: 0,+ isOnScreen: () => true,+ }),TranslationKeys: {},}));@@ -126,6 +132,8 @@ describe('Conversations: pinned chats live in PinnedSection', () => {isSearchLoading={false}isChatsExpanded={true}setIsChatsExpanded={jest.fn()}+ scrollViewport={null}+ scrollContent={null}/></RecoilRoot></DndProvider>@@ -180,6 +188,8 @@ describe('Conversations: all-pin pages still paginate', () => {isChatsExpanded={isChatsExpanded}setIsChatsExpanded={jest.fn()}hasNextPage={hasNextPage}+ scrollViewport={null}+ scrollContent={null}/></RecoilRoot></DndProvider>@@ -256,6 +266,8 @@ describe('Conversations: all-pin pages still paginate', () => {isSearchLoading={false}isChatsExpanded={true}setIsChatsExpanded={jest.fn()}+ scrollViewport={null}+ scrollContent={null}/></RecoilRoot></DndProvider>@@ -275,6 +287,8 @@ describe('Conversations: all-pin pages still paginate', () => {isSearchLoading={false}isChatsExpanded={true}setIsChatsExpanded={jest.fn()}+ scrollViewport={null}+ scrollContent={null}/></RecoilRoot></DndProvider>diff --git a/client/src/components/UnifiedSidebar/ConversationsSection.tsx b/client/src/components/UnifiedSidebar/ConversationsSection.tsxindex 937f96f50e..b00f610516 100644--- a/client/src/components/UnifiedSidebar/ConversationsSection.tsx+++ b/client/src/components/UnifiedSidebar/ConversationsSection.tsx@@ -156,6 +156,24 @@ const ConversationsSection = memo(() => {}}, [search.query, search.isTyping, isLoading, isFetching]);+ /** Projects, Pinned and Chats share one scroll container so the sidebar scrolls+ * as a single surface: the chats list is virtualized against this viewport+ * rather than scrolling inside a pane of its own. */+ const [scrollViewport, setScrollViewport] = useState<HTMLDivElement | null>(null);+ const [scrollContent, setScrollContent] = useState<HTMLDivElement | null>(null);++ /** Searching replaces what the surface holds: Projects and Pinned leave and+ * the chats become results. A scroll position kept from the previous+ * contents would open those results partway down whenever they are long+ * enough for the browser not to clamp it, so the surface returns to the top+ * whenever it changes what it is showing. */+ const isSearching = Boolean(search.query);+ useEffect(() => {+ if (scrollViewport) {+ scrollViewport.scrollTop = 0;+ }+ }, [isSearching, scrollViewport]);+return (<divclassName="flex h-full min-h-0 flex-col overflow-hidden pb-3 pt-2"@@ -170,37 +188,48 @@ const ConversationsSection = memo(() => {<SearchBar isSmallScreen={isSmallScreen} /></div>)}- {!search.query && <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />}- {!search.query && (- <PinnedSection- conversations={pinnedConversations}- toggleNav={toggleNav}- isSmallScreen={isSmallScreen}- /* Only a successful drain proves the list is whole: a failed later- page still publishes partial data and stops fetching. The Chats filters- never reach this query, so nothing else can truncate it. */- membershipComplete={isPinnedComplete}- /* When that drain last ran, which decides whether it is current- enough to prune the stored order against. */- membershipUpdatedAt={pinnedUpdatedAt}- />- )}- <div className="flex min-h-0 flex-grow flex-col overflow-hidden">- <Conversations- conversations={conversations}- moveToTop={moveToTop}- toggleNav={toggleNav}- containerRef={conversationsRef}- loadMoreConversations={loadMoreConversations}- isLoading={isFetchingNextPage || isLoading}- isSearchLoading={isSearchLoading || isPreviousData}- isChatsExpanded={isChatsExpanded}- setIsChatsExpanded={setIsChatsExpanded}- hasNextPage={computedHasNextPage}- isError={isError}- onRetry={retryConversations}- chatsHeaderTrailing={chatsHeaderTrailing}- />+ <div+ ref={setScrollViewport}+ className="scrollbar-gutter-stable min-h-0 flex-1 overflow-y-auto overflow-x-hidden"+ >+ {/* `min-h-full` keeps the sections filling a tall sidebar, so the chats+ list still claims the space below them when there is little to show. */}+ <div ref={setScrollContent} className="flex min-h-full flex-col">+ {!search.query && (+ <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />+ )}+ {!search.query && (+ <PinnedSection+ conversations={pinnedConversations}+ toggleNav={toggleNav}+ isSmallScreen={isSmallScreen}+ /* Only a successful drain proves the list is whole: a failed later+ page still publishes partial data and stops fetching. The Chats filters+ never reach this query, so nothing else can truncate it. */+ membershipComplete={isPinnedComplete}+ /* When that drain last ran, which decides whether it is current+ enough to prune the stored order against. */+ membershipUpdatedAt={pinnedUpdatedAt}+ />+ )}+ <Conversations+ conversations={conversations}+ moveToTop={moveToTop}+ toggleNav={toggleNav}+ containerRef={conversationsRef}+ loadMoreConversations={loadMoreConversations}+ isLoading={isFetchingNextPage || isLoading}+ isSearchLoading={isSearchLoading || isPreviousData}+ isChatsExpanded={isChatsExpanded}+ setIsChatsExpanded={setIsChatsExpanded}+ hasNextPage={computedHasNextPage}+ isError={isError}+ onRetry={retryConversations}+ chatsHeaderTrailing={chatsHeaderTrailing}+ scrollViewport={scrollViewport}+ scrollContent={scrollContent}+ />+ </div></div></div>);diff --git a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsxindex 67f1d483b6..a6738fec80 100644--- a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx+++ b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx@@ -6,6 +6,7 @@ import { HTML5Backend } from 'react-dnd-html5-backend';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { atom, RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';import type { SetterOrUpdater } from 'recoil';+import type { SearchState } from '~/store/search';/*** Real recoil atom used to force ConversationsSection to re-render on demand,@@ -135,6 +136,7 @@ jest.mock('~/components/Nav/Favorites/FavoriteItem', () => ({}));import ConversationsSection from '../ConversationsSection';+import store from '~/store';let setStreamTick: SetterOrUpdater<number>;@@ -240,3 +242,47 @@ describe('ConversationsSection streaming re-renders', () => {TEST_TIMEOUT,);});++describe('ConversationsSection shared scroll surface', () => {+ /** Searching swaps what the one surface holds — Projects and Pinned leave,+ * the chats become results — and a position kept from the previous contents+ * would open those results partway down. */+ it('returns the surface to the top when a search replaces its contents', async () => {+ let setSearch: SetterOrUpdater<SearchState>;++ function SearchController() {+ setSearch = useSetRecoilState(store.search);+ return null;+ }++ const { container } = render(+ <QueryClientProvider client={createQueryClient()}>+ <RecoilRoot>+ <BrowserRouter>+ <DndProvider backend={HTML5Backend}>+ <SearchController />+ <ConversationsSection />+ </DndProvider>+ </BrowserRouter>+ </RecoilRoot>+ </QueryClientProvider>,+ );+ await settleRenders();++ const surface = container.querySelector<HTMLElement>('.overflow-y-auto');+ expect(surface).not.toBeNull();+ surface!.scrollTop = 420;++ act(() => {+ setSearch({+ query: 'draft',+ debouncedQuery: 'draft',+ enabled: true,+ isTyping: false,+ isSearching: true,+ });+ });++ expect(surface!.scrollTop).toBe(0);+ });+});diff --git a/client/src/hooks/Generic/__tests__/useOuterScrollWindow.spec.tsx b/client/src/hooks/Generic/__tests__/useOuterScrollWindow.spec.tsxnew file mode 100644index 0000000000..c166f772dc--- /dev/null+++ b/client/src/hooks/Generic/__tests__/useOuterScrollWindow.spec.tsx@@ -0,0 +1,287 @@+import { renderHook, act } from '@testing-library/react';+import useOuterScrollWindow from '../useOuterScrollWindow';++class MockResizeObserver {+ static instances: MockResizeObserver[] = [];+ callback: ResizeObserverCallback;+ observed: Element[] = [];+ disconnected = false;++ constructor(callback: ResizeObserverCallback) {+ this.callback = callback;+ MockResizeObserver.instances.push(this);+ }++ observe(element: Element) {+ this.observed.push(element);+ }++ unobserve() {}++ disconnect() {+ this.disconnected = true;+ }++ /** Reports a size change for everything it watches, the way a collapsing+ * section above the list reaches the hook. */+ trigger() {+ this.callback([] as unknown as ResizeObserverEntry[], this as unknown as ResizeObserver);+ }+}++/** Frames run only when the test says so, which is how coalescing is observed:+ * several scroll events must leave one pending frame, not one each. */+class FrameQueue {+ pending = new Map<number, FrameRequestCallback>();+ private next = 1;++ request = (callback: FrameRequestCallback): number => {+ const handle = this.next++;+ this.pending.set(handle, callback);+ return handle;+ };++ cancel = (handle: number): void => {+ this.pending.delete(handle);+ };++ flush(): number {+ const callbacks = [...this.pending.values()];+ this.pending.clear();+ callbacks.forEach((callback) => callback(performance.now()));+ return callbacks.length;+ }+}++const setRect = (element: HTMLElement, top: number, height: number) => {+ element.getBoundingClientRect = () =>+ ({+ top,+ bottom: top + height,+ height,+ left: 0,+ right: 0,+ width: 0,+ x: 0,+ y: top,+ toJSON: () => ({}),+ }) as DOMRect;+};++const setClientHeight = (element: HTMLElement, height: number) => {+ Object.defineProperty(element, 'clientHeight', { value: height, configurable: true });+};++/**+ * A scroll viewport holding a wrapper, with the windowed node laid out below+ * some other content: the node's top sits `offset` pixels into the wrapper.+ */+function layout({ offset, viewportHeight = 500 }: { offset: number; viewportHeight?: number }) {+ const viewport = document.createElement('div');+ const content = document.createElement('div');+ const node = document.createElement('div');+ content.appendChild(node);+ viewport.appendChild(content);+ document.body.appendChild(viewport);++ setClientHeight(viewport, viewportHeight);+ setRect(viewport, 0, viewportHeight);+ setRect(content, 0, 3000);+ setRect(node, offset, 2000);++ /** Moves the viewport's scroll position, with the rects the browser would+ * report at that offset: everything inside shifts up by the same amount. */+ const scrollTo = (scrollTop: number, nodeOffset = offset) => {+ viewport.scrollTop = scrollTop;+ setRect(node, nodeOffset - scrollTop, 2000);+ };++ return { viewport, content, node, scrollTo };+}++describe('useOuterScrollWindow', () => {+ const originalResizeObserver = window.ResizeObserver;+ const originalRaf = window.requestAnimationFrame;+ const originalCancelRaf = window.cancelAnimationFrame;+ let frames: FrameQueue;++ beforeEach(() => {+ MockResizeObserver.instances = [];+ window.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;+ frames = new FrameQueue();+ window.requestAnimationFrame = frames.request as typeof window.requestAnimationFrame;+ window.cancelAnimationFrame = frames.cancel as typeof window.cancelAnimationFrame;+ });++ afterEach(() => {+ window.ResizeObserver = originalResizeObserver;+ window.requestAnimationFrame = originalRaf;+ window.cancelAnimationFrame = originalCancelRaf;+ document.body.innerHTML = '';+ });++ it('reports nothing until a viewport and a node are both attached', () => {+ const { viewport } = layout({ offset: 200 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, null));++ expect(result.current).toMatchObject({ height: 0, scrollTop: 0 });+ });++ it('windows only the slice of the list the viewport shows', () => {+ const { viewport, content, node, scrollTo } = layout({ offset: 200 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));++ /** 200px of other content sits above it in a 500px viewport. */+ expect(result.current.height).toBe(300);+ expect(result.current.scrollTop).toBe(0);++ act(() => {+ scrollTo(120);+ viewport.dispatchEvent(new Event('scroll'));+ frames.flush();+ });++ /** Scrolled less than the content above the list: the list has not started+ * moving through the viewport yet, it has only grown into it. */+ expect(result.current.scrollTop).toBe(0);+ expect(result.current.height).toBe(420);+ });++ it('keeps a single pixel of window while the list sits below the fold', () => {+ const { viewport, content, node } = layout({ offset: 700 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));++ /** Not a screenful — nothing of it is on display — but not nothing either:+ * a list told it has no window renders no rows, and a list that renders+ * no rows has no height to be scrolled into view with. Anything that must+ * know whether the reader can see it asks, rather than reading a height+ * that is deliberately never zero. */+ expect(result.current.height).toBe(1);+ expect(result.current.isOnScreen()).toBe(false);+ });++ it('reports the list as on screen as soon as it reaches the fold', () => {+ const { viewport, content, node, scrollTo } = layout({ offset: 700 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));+ expect(result.current.isOnScreen()).toBe(false);++ act(() => {+ scrollTo(260);+ viewport.dispatchEvent(new Event('scroll'));+ frames.flush();+ });++ expect(result.current.isOnScreen()).toBe(true);+ expect(result.current.height).toBe(60);+ });++ it('answers from the layout as it stands, not from the last frame', () => {+ const { viewport, content, node } = layout({ offset: 700 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));+ expect(result.current.isOnScreen()).toBe(false);++ /** A commit that swaps what the viewport holds moves the list before any+ * observer or frame has run: a caller acting inside that commit must not+ * be told where the list used to be. No scroll event, no frame flushed. */+ setRect(node, 100, 2000);+ expect(result.current.isOnScreen()).toBe(true);++ setRect(node, 900, 2000);+ expect(result.current.isOnScreen()).toBe(false);+ });++ it('translates the viewport scroll into the list own coordinates', () => {+ const { viewport, content, node, scrollTo } = layout({ offset: 200 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));++ act(() => {+ scrollTo(900);+ viewport.dispatchEvent(new Event('scroll'));+ frames.flush();+ });++ expect(result.current.scrollTop).toBe(700);+ });++ it('coalesces a burst of scroll events into one measurement', () => {+ const { viewport, content, node, scrollTo } = layout({ offset: 200 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));++ act(() => {+ for (const top of [300, 400, 500]) {+ scrollTo(top);+ viewport.dispatchEvent(new Event('scroll'));+ }+ expect(frames.pending.size).toBe(1);+ frames.flush();+ });++ /** The single frame reads the position the burst ended at. */+ expect(result.current.scrollTop).toBe(300);+ });++ it('re-measures when a section above the list collapses', () => {+ const { viewport, content, node, scrollTo } = layout({ offset: 400 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));++ act(() => {+ scrollTo(900);+ viewport.dispatchEvent(new Event('scroll'));+ frames.flush();+ });+ expect(result.current.scrollTop).toBe(500);++ /** The section above shrinks by 150px: no scroll event, no viewport or list+ * resize — only the wrapper's height changes, and the list has moved up. */+ act(() => {+ setRect(node, 400 - 150 - 900, 2000);+ setRect(content, 0, 2850);+ MockResizeObserver.instances.forEach((observer) => observer.trigger());+ frames.flush();+ });++ expect(result.current.scrollTop).toBe(650);+ });++ it('watches the wrapper for layout changes when ResizeObserver is unavailable', () => {+ window.ResizeObserver = undefined as unknown as typeof ResizeObserver;+ const { viewport, content, node } = layout({ offset: 400 });+ const { result } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));++ viewport.scrollTop = 900;+ setRect(node, 400 - 900, 2000);+ act(() => {+ content.dispatchEvent(new Event('transitionend', { bubbles: true }));+ frames.flush();+ });+ expect(result.current.scrollTop).toBe(500);++ /** The collapse that shortens the wrapper reaches the hook the same way. */+ setRect(node, 400 - 150 - 900, 2000);+ act(() => {+ content.dispatchEvent(new Event('transitionend', { bubbles: true }));+ frames.flush();+ });+ expect(result.current.scrollTop).toBe(650);+ });++ it('stops listening when the consumer unmounts', () => {+ const { viewport, content, node } = layout({ offset: 200 });+ const removeListener = jest.spyOn(viewport, 'removeEventListener');+ const { result, unmount } = renderHook(() => useOuterScrollWindow(viewport, content));+ act(() => result.current.ref(node));++ unmount();++ expect(MockResizeObserver.instances.every((observer) => observer.disconnected)).toBe(true);+ expect(removeListener).toHaveBeenCalledWith('scroll', expect.any(Function));+ });+});diff --git a/client/src/hooks/Generic/index.ts b/client/src/hooks/Generic/index.tsindex 2dc02f273b..2a28c53bbc 100644--- a/client/src/hooks/Generic/index.ts+++ b/client/src/hooks/Generic/index.ts@@ -1,3 +1,4 @@export * from './useLazyEffect';export { default as useShiftKey } from './useShiftKey';export { default as useElementSize } from './useElementSize';+export { default as useOuterScrollWindow } from './useOuterScrollWindow';diff --git a/client/src/hooks/Generic/useOuterScrollWindow.ts b/client/src/hooks/Generic/useOuterScrollWindow.tsnew file mode 100644index 0000000000..2492ca8c7f--- /dev/null+++ b/client/src/hooks/Generic/useOuterScrollWindow.ts@@ -0,0 +1,153 @@+import { useCallback, useEffect, useRef, useState } from 'react';++interface OuterScrollWindow {+ /** Attach to the element the windowed content starts at. */+ ref: (node: HTMLElement | null) => void;+ /** Height of the attached element that is actually on screen: a single pixel+ * while it sits below the fold, the viewport's height once it fills it. */+ height: number;+ /** Viewport scroll offset expressed in the attached element's own coordinates. */+ scrollTop: number;+ /** Whether any of the attached element is on screen, read from the layout at+ * the moment it is asked. The height cannot answer this — it keeps a pixel+ * for an element nobody can see, so that the element still has a size to be+ * scrolled to — and a stored answer cannot either: a commit that swaps what+ * the viewport holds moves the element before any observer has run, and a+ * caller acting during that commit would act on the previous layout. */+ isOnScreen: () => boolean;+}++/**+ * Translates an ancestor's scroll position into the coordinates of a descendant,+ * so a virtualized list can be windowed by a scroll container it does not own —+ * the list renders at its natural height and the outer container scrolls it.+ *+ * `content` is the wrapper holding everything inside the viewport: siblings above+ * the list (collapsible sections) change the list's offset without resizing either+ * the viewport or the list, and observing that wrapper is what catches those.+ */+export default function useOuterScrollWindow(+ viewport: HTMLElement | null,+ content: HTMLElement | null,+): OuterScrollWindow {+ const [node, setNode] = useState<HTMLElement | null>(null);+ const [metrics, setMetrics] = useState({ height: 0, scrollTop: 0 });++ const ref = useCallback((element: HTMLElement | null) => setNode(element), []);++ /** The probe reads whatever is current rather than what the last frame saw,+ * so it is held through refs instead of closing over a render's values. */+ const viewportRef = useRef(viewport);+ viewportRef.current = viewport;+ const nodeRef = useRef(node);+ nodeRef.current = node;++ const isOnScreen = useCallback(() => {+ const currentViewport = viewportRef.current;+ const currentNode = nodeRef.current;+ if (!currentViewport || !currentNode) {+ return false;+ }+ const nodeRect = currentNode.getBoundingClientRect();+ const viewportRect = currentViewport.getBoundingClientRect();+ return (+ Math.min(nodeRect.bottom, viewportRect.bottom) > Math.max(nodeRect.top, viewportRect.top)+ );+ }, []);++ useEffect(() => {+ if (!viewport || !node) {+ return;+ }++ const measure = () => {+ /** Read against the viewport rather than `offsetTop`, whose origin is the+ * nearest positioned ancestor and so moves with unrelated styling. */+ const nodeRect = node.getBoundingClientRect();+ const viewportRect = viewport.getBoundingClientRect();+ const offsetTop = nodeRect.top - viewportRect.top + viewport.scrollTop;+ /** The window is the slice of the element the viewport actually shows.+ * Reporting the whole viewport instead would have a list that is still+ * below the fold believe a screenful of it is on display, and anything+ * windowing on that — row rendering, reaching the end of a page — would+ * act before the reader has seen a row of it.+ *+ * The floor of one pixel is what keeps that honest window from becoming+ * a trap: a windowed list renders nothing at zero, and a list that+ * renders nothing reports no height, so the container it sits in would+ * never grow enough to scroll it into view. One pixel renders its first+ * row, which is what gives the list its own height back. */+ const onScreen =+ Math.min(nodeRect.bottom, viewportRect.bottom) - Math.max(nodeRect.top, viewportRect.top);+ const next = {+ height: Math.max(1, Math.round(onScreen)),+ scrollTop: Math.max(0, viewport.scrollTop - offsetTop),+ };+ setMetrics((prev) =>+ prev.height === next.height && prev.scrollTop === next.scrollTop ? prev : next,+ );+ };++ let frame = 0;+ const schedule = () => {+ if (frame !== 0) {+ return;+ }+ frame = requestAnimationFrame(() => {+ frame = 0;+ measure();+ });+ };++ measure();+ viewport.addEventListener('scroll', schedule, { passive: true });++ /** A section collapsing above the attached node moves it without resizing+ * the viewport or the node, and without a scroll event: observing the+ * content wrapper is what reports that. Where `ResizeObserver` is missing+ * the same layout change still announces itself — the collapse mutates+ * the wrapper's DOM and its height tween ends with a bubbling+ * `transitionend` — so the fallback keeps the trigger rather than+ * dropping the invariant to window resizes alone. */+ let resizeObserver: ResizeObserver | undefined;+ let mutationObserver: MutationObserver | undefined;+ if (typeof ResizeObserver !== 'undefined') {+ resizeObserver = new ResizeObserver(schedule);+ resizeObserver.observe(viewport);+ if (content) {+ resizeObserver.observe(content);+ }+ } else {+ window.addEventListener('resize', schedule);+ if (content) {+ content.addEventListener('transitionend', schedule);+ content.addEventListener('animationend', schedule);+ mutationObserver = new MutationObserver(schedule);+ mutationObserver.observe(content, {+ attributes: true,+ childList: true,+ subtree: true,+ });+ }+ }++ return () => {+ viewport.removeEventListener('scroll', schedule);+ resizeObserver?.disconnect();+ mutationObserver?.disconnect();+ window.removeEventListener('resize', schedule);+ content?.removeEventListener('transitionend', schedule);+ content?.removeEventListener('animationend', schedule);+ if (frame !== 0) {+ cancelAnimationFrame(frame);+ }+ };+ }, [viewport, content, node]);++ return {+ ref,+ height: metrics.height,+ scrollTop: metrics.scrollTop,+ isOnScreen,+ };+}diff --git a/e2e/specs/mock/scenarios/sidebar-single-scroll.spec.ts b/e2e/specs/mock/scenarios/sidebar-single-scroll.spec.tsnew file mode 100644index 0000000000..008107d301--- /dev/null+++ b/e2e/specs/mock/scenarios/sidebar-single-scroll.spec.ts@@ -0,0 +1,478 @@+import { randomUUID } from 'crypto';+import { expect, test } from '@playwright/test';+import type { Locator, Page } from '@playwright/test';+import { getE2EUser } from '../../../setup/user';+import { clearUserConversations, seedConversations, withMongo } from '../db';+import type { SeedConvo } from '../db';++/* Seeding a list long enough to scroll, then loading the app against a database+ * that may be a network hop away, is the slow part of every test here and it+ * runs in hooks, which do not read a `test.setTimeout` made in a test body. */+test.describe.configure({ timeout: 120_000 });++const userEmail = getE2EUser().email;++/** `aria-label` of the sidebar's chat-history region (`com_ui_chat_history`). */+const HISTORY_REGION = 'Chat History';+/** `aria-label` of the Pinned section's region (`com_ui_pinned`). */+const PINNED_REGION = 'Pinned';++const historyRegion = (page: Page): Locator => page.getByRole('region', { name: HISTORY_REGION });+const pinnedRegion = (page: Page): Locator => page.getByRole('region', { name: PINNED_REGION });++type Seeded = { conversationId: string; title: string };++const titleOf = (prefix: string, index: number) => `${prefix} ${String(index).padStart(3, '0')}`;++/** Chats, newest first: index 0 is the top row, the last index the oldest. */+async function seedChats(prefix: string, count: number): Promise<Seeded[]> {+ const noon = new Date();+ noon.setHours(12, 0, 0, 0);+ const base = noon.getTime();+ const convos: SeedConvo[] = Array.from({ length: count }, (_, index) => ({+ conversationId: randomUUID(),+ title: titleOf(prefix, index),+ updatedAt: new Date(base - index * 1000),+ }));+ await seedConversations(userEmail, convos);+ return convos.map(({ conversationId, title }) => ({ conversationId, title }));+}++/** Pinned chats are ordinary conversations carrying `pinned: true`; the sidebar+ * lifts them out of the date groups into the Pinned section. `ageDays` backs+ * them out of the recent window, for a spec that needs the first page of the+ * chats query to be chats rather than the pins it strips back out. */+async function seedPins(prefix: string, count: number, ageDays = 0): Promise<Seeded[]> {+ const now = Date.now() - ageDays * 24 * 60 * 60 * 1000;+ const pins: Seeded[] = Array.from({ length: count }, (_, index) => ({+ conversationId: randomUUID(),+ title: titleOf(prefix, index),+ }));+ await withMongo(async (db) => {+ const user = await db.collection('users').findOne({ email: userEmail });+ if (!user) {+ throw new Error(`E2E seed: user "${userEmail}" not found`);+ }+ await db.collection('conversations').insertMany(+ pins.map((pin, index) => ({+ conversationId: pin.conversationId,+ title: pin.title,+ user: String(user._id),+ endpoint: 'openAI',+ isArchived: false,+ pinned: true,+ createdAt: new Date(now - index * 1000),+ updatedAt: new Date(now - index * 1000),+ __v: 0,+ })),+ );+ });+ return pins;+}++/**+ * Brings the sidebar on screen. A narrow viewport keeps the drawer mounted and+ * slides it out of view instead of unmounting it, so every row still answers a+ * query while nothing on it can be scrolled — the wheel would land on the page+ * beside the drawer. The chat header's opener is what a person reaches for+ * there, and it only exists once that header has rendered, so the click is+ * retried rather than taken once. Desktop renders no opener at all, where a+ * box still left of the origin is a panel mid-layout, not a closed drawer.+ */+async function openSidebar(page: Page): Promise<void> {+ await expect(historyRegion(page)).toBeVisible({ timeout: 30_000 });+ const placement = async () => {+ const box = await historyRegion(page).boundingBox();+ return box === null ? 'unlaid' : box.x >= 0 ? 'on-screen' : 'off-screen';+ };+ await expect.poll(placement, { timeout: 30_000 }).not.toBe('unlaid');+ for (let attempt = 0; attempt < 3 && (await placement()) === 'off-screen'; attempt++) {+ const opener = page.getByRole('button', { name: 'Open sidebar' }).first();+ if (await opener.isVisible().catch(() => false)) {+ await opener.click();+ }+ await expect+ .poll(placement, { timeout: 10_000 })+ .toBe('on-screen')+ .catch(() => undefined);+ }+ await expect.poll(placement, { timeout: 15_000 }).toBe('on-screen');+}++type Surface = { top: number; height: number; scrollTop: number; scrollHeight: number };++/**+ * Every descendant of the chat-history region that actually scrolls. The whole+ * point of the single surface is that this is one element: the sections above+ * the chats no longer keep scrollable boxes of their own.+ */+const scrollingSurfaces = (page: Page): Promise<Surface[]> =>+ historyRegion(page).evaluate((region) =>+ Array.from(region.querySelectorAll('*'))+ .filter((node) => {+ const style = getComputedStyle(node);+ const scrolls = style.overflowY === 'auto' || style.overflowY === 'scroll';+ return scrolls && node.scrollHeight > node.clientHeight + 1;+ })+ .map((node) => {+ const rect = node.getBoundingClientRect();+ return {+ top: rect.top,+ height: rect.height,+ scrollTop: node.scrollTop,+ scrollHeight: node.scrollHeight,+ };+ }),+ );++const sidebarScrollTop = async (page: Page): Promise<number> => {+ const [surface] = await scrollingSurfaces(page);+ return surface?.scrollTop ?? 0;+};++/** Moves the sidebar's own scroll surface, for the emulated touch devices+ * where a wheel gesture is not what a person would produce. */+const dragSurface = (page: Page, deltaY: number) =>+ historyRegion(page).evaluate((region, delta) => {+ const surface = Array.from(region.querySelectorAll('*')).find((node) => {+ const style = getComputedStyle(node);+ return (+ (style.overflowY === 'auto' || style.overflowY === 'scroll') &&+ node.scrollHeight > node.clientHeight + 1+ );+ });+ surface?.scrollBy(0, delta);+ }, deltaY);++/**+ * Scrolls the sidebar the way a person does: the wheel turns over a point+ * inside it and whatever surface is under the pointer takes the gesture. The+ * pointer is deliberately placed over the rows rather than over some scrollbar,+ * because "one scroll" is a claim about what happens under the content. Touch+ * emulation produces no wheel, so there the same surface is driven directly.+ */+async function scrollSidebar(page: Page, deltaY: number): Promise<number> {+ const box = await historyRegion(page).boundingBox();+ expect(box, 'the chat-history region should be laid out').not.toBeNull();+ const before = await sidebarScrollTop(page);+ await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2);+ await page.mouse.wheel(0, deltaY);+ await expect+ .poll(() => sidebarScrollTop(page), { timeout: 3_000 })+ .not.toBe(before)+ .catch(() => undefined);+ if ((await sidebarScrollTop(page)) === before) {+ await dragSurface(page, deltaY);+ }+ await expect.poll(() => sidebarScrollTop(page), { timeout: 10_000 }).not.toBe(before);+ return sidebarScrollTop(page);+}++/** Scrolls to the end of the sidebar, following the list as later pages load. */+async function scrollToBottom(page: Page, turns: number): Promise<void> {+ for (let turn = 0; turn < turns; turn++) {+ const box = await historyRegion(page).boundingBox();+ if (!box) {+ return;+ }+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);+ await page.mouse.wheel(0, 2000);+ await dragSurface(page, 2000);+ await page.waitForTimeout(400);+ }+}++/**+ * Samples the visible band of the chats list for painted rows. A list windowed+ * against a stale offset renders the wrong slice, which shows up as points+ * inside the band that land on no row at all.+ */+const bandSample = (page: Page) =>+ historyRegion(page).evaluate((region) => {+ const grid = region.querySelector('.ReactVirtualized__Grid');+ const surface = Array.from(region.querySelectorAll('*')).find((node) => {+ const style = getComputedStyle(node);+ return (+ (style.overflowY === 'auto' || style.overflowY === 'scroll') &&+ node.scrollHeight > node.clientHeight + 1+ );+ });+ if (!grid || !surface) {+ return { rows: [] as string[], holes: [] as number[] };+ }+ const gridRect = grid.getBoundingClientRect();+ const viewRect = surface.getBoundingClientRect();+ const top = Math.max(gridRect.top, viewRect.top) + 6;+ const bottom = Math.min(gridRect.bottom, viewRect.bottom) - 6;+ const x = viewRect.left + viewRect.width / 2;+ const rows: string[] = [];+ const holes: number[] = [];+ for (let y = top; y < bottom; y += 16) {+ const node = document.elementFromPoint(x, y);+ const row = node?.closest('[data-testid="convo-item"], [data-testid="convo-list-row"]');+ if (row) {+ const title = (row.textContent ?? '').trim().split('\n')[0];+ if (title && rows[rows.length - 1] !== title) {+ rows.push(title);+ }+ } else {+ holes.push(Math.round(y - viewRect.top));+ }+ }+ return { rows, holes };+ });++/** Every page the chats list asks the server for, as it asks for it. The pinned+ * query rides the same route and is left out: it is not the list's paging. */+function trackChatPages(page: Page): string[] {+ const pages: string[] = [];+ page.on('request', (request) => {+ const { pathname, searchParams } = new URL(request.url());+ if (request.method() === 'GET' && pathname === '/api/convos' && !searchParams.has('pinned')) {+ pages.push(request.url());+ }+ });+ return pages;+}++/** Waits until the chats list starts past the bottom edge of the surface. */+const waitForChatsBelowTheFold = (page: Page) =>+ expect+ .poll(+ () =>+ historyRegion(page).evaluate((region) => {+ const grid = region.querySelector('.ReactVirtualized__Grid');+ const surface = Array.from(region.querySelectorAll('*')).find((node) => {+ const style = getComputedStyle(node);+ return style.overflowY === 'auto' || style.overflowY === 'scroll';+ });+ if (!grid || !surface) {+ return false;+ }+ return grid.getBoundingClientRect().top >= surface.getBoundingClientRect().bottom;+ }),+ { timeout: 30_000 },+ )+ .toBe(true);++const seeded: Seeded[] = [];++const remember = (rows: Seeded[]): Seeded[] => {+ seeded.push(...rows);+ return rows;+};++test.afterEach(async () => {+ seeded.length = 0;+ await clearUserConversations(userEmail);+});++test.describe('sidebar single scroll', () => {+ test('the whole sidebar scrolls as one surface @scenario:sidebar-scrolls-as-one-surface', async ({+ page,+ }) => {+ await clearUserConversations(userEmail);+ remember(await seedPins('E2E pin', 4));+ remember(await seedChats('E2E chat', 40));++ await page.goto('/c/new', { timeout: 30_000 });+ await openSidebar(page);+ await expect(pinnedRegion(page)).toBeVisible({ timeout: 30_000 });+ await expect(page.getByTestId('convo-item').first()).toBeVisible({ timeout: 30_000 });++ const surfaces = await scrollingSurfaces(page);+ expect(surfaces, 'the sidebar should present exactly one scrolling surface').toHaveLength(1);++ const pinnedBefore = await pinnedRegion(page).boundingBox();+ expect(pinnedBefore).not.toBeNull();++ const scrolled = await scrollSidebar(page, 400);+ expect(scrolled).toBeGreaterThan(0);++ /* The Pinned section rides the same gesture instead of staying put: it+ * moves up by what the surface scrolled. */+ await expect+ .poll(+ async () => {+ const after = await pinnedRegion(page).boundingBox();+ return after === null ? null : Math.round(pinnedBefore!.y - after.y);+ },+ { timeout: 10_000 },+ )+ .toBeGreaterThan(100);++ const sample = await bandSample(page);+ expect(sample.holes, 'the visible list should be fully painted').toEqual([]);+ expect(sample.rows.length).toBeGreaterThan(0);+ });++ test('older chats load as the sidebar scrolls to its end @scenario:older-chats-load-as-the-sidebar-scrolls', async ({+ page,+ }) => {+ await clearUserConversations(userEmail);+ const chats = remember(await seedChats('E2E page', 60));+ const oldest = chats[chats.length - 1].title;++ await page.goto('/c/new', { timeout: 30_000 });+ await openSidebar(page);+ await expect(page.getByTestId('convo-item').first()).toBeVisible({ timeout: 30_000 });++ const oldestRow = page.getByTestId('convo-item').filter({ hasText: oldest });+ expect(await oldestRow.count(), 'the oldest chat should still be beyond the first page').toBe(+ 0,+ );++ await scrollToBottom(page, 12);++ await expect(oldestRow.first()).toBeVisible({ timeout: 30_000 });+ });++ test('collapsing a section keeps the visible chats in place @scenario:collapsing-a-section-keeps-the-visible-chats-in-place', async ({+ page,+ }) => {+ await clearUserConversations(userEmail);+ remember(await seedPins('E2E pin', 6));+ remember(await seedChats('E2E chat', 50));++ await page.goto('/c/new', { timeout: 30_000 });+ await openSidebar(page);+ await expect(pinnedRegion(page)).toBeVisible({ timeout: 30_000 });+ await expect(page.getByTestId('convo-item').first()).toBeVisible({ timeout: 30_000 });++ await scrollSidebar(page, 600);+ const before = await bandSample(page);+ expect(before.holes).toEqual([]);+ expect(before.rows.length).toBeGreaterThan(1);++ /* Collapsing a section above the chats shortens the surface without+ * resizing either the viewport or the list, which is exactly the change+ * that leaves a windowed list painting the wrong slice. */+ await pinnedRegion(page).getByRole('button', { name: PINNED_REGION }).click();+ await expect(pinnedRegion(page).getByRole('button', { name: PINNED_REGION })).toHaveAttribute(+ 'aria-expanded',+ 'false',+ );+ await page.waitForTimeout(600);++ const after = await bandSample(page);+ expect(after.holes, 'the list should stay painted after the collapse').toEqual([]);+ expect(+ after.rows.some((title) => before.rows.includes(title)),+ `chats on screen before the collapse (${before.rows.join(', ')}) should still be there, got ${after.rows.join(', ')}`,+ ).toBe(true);+ });++ test('a long pinned list scrolls with the sidebar @scenario:pinned-list-scrolls-with-the-sidebar', async ({+ page,+ }) => {+ await clearUserConversations(userEmail);+ remember(await seedPins('E2E pin', 20));+ remember(await seedChats('E2E chat', 30));++ await page.goto('/c/new', { timeout: 30_000 });+ await openSidebar(page);+ await expect(pinnedRegion(page)).toBeVisible({ timeout: 30_000 });++ const pinnedScrollers = await pinnedRegion(page).evaluate(+ (region) =>+ Array.from(region.querySelectorAll('*')).filter((node) => {+ const style = getComputedStyle(node);+ return (+ (style.overflowY === 'auto' || style.overflowY === 'scroll') &&+ node.scrollHeight > node.clientHeight + 1+ );+ }).length,+ );+ expect(pinnedScrollers, 'the pinned list should not scroll inside its own box').toBe(0);++ const firstPin = pinnedRegion(page).getByTestId('convo-item').first();+ const before = await firstPin.boundingBox();+ expect(before).not.toBeNull();++ await scrollSidebar(page, 300);++ await expect+ .poll(+ async () => {+ const after = await firstPin.boundingBox();+ return after === null ? null : Math.round(before!.y - after.y);+ },+ { timeout: 10_000 },+ )+ .toBeGreaterThan(100);+ });++ test('chats stop fetching pages while they sit below the fold @scenario:chats-page-loads-only-when-chats-come-into-view', async ({+ page,+ }) => {+ await clearUserConversations(userEmail);+ /* Enough pins to hold the chats list below the fold on both a desktop+ * panel and an emulated handset, and old enough that the first page of the+ * chats query is chats: pins ride that query too, and a page made only of+ * rows the list strips back out has its own reason to fetch another. */+ remember(await seedPins('E2E pin', 24, 400));+ remember(await seedChats('E2E chat', 60));++ const pages = trackChatPages(page);++ await page.goto('/c/new', { timeout: 30_000 });+ await openSidebar(page);+ await expect(pinnedRegion(page).getByTestId('convo-item').first()).toBeVisible({+ timeout: 30_000,+ });++ /** The pins arrive on their own query, so until they land the chats hold+ * the sidebar and reading them is exactly what a person does. The claim+ * is about the settled layout: once the chats sit below a screenful of+ * pins, nothing keeps asking the server for more of them. */+ await waitForChatsBelowTheFold(page);++ const settled = pages.length;+ await page.waitForTimeout(3_000);+ expect(+ pages.length,+ `no page should be fetched for chats nobody can see, got ${pages.join(', ')}`,+ ).toBe(settled);++ /* Kept scrolling until the list answers, the way a reader does: one burst+ * lands wherever the rows rendered so far end, and the list grows as they+ * are measured. */+ for (let turn = 0; turn < 12 && pages.length === settled; turn++) {+ await scrollToBottom(page, 2);+ }+ await expect.poll(() => pages.length, { timeout: 30_000 }).toBeGreaterThan(settled);+ });++ test('a page whose chats are nearly all pinned waits for the reader too @scenario:mostly-pinned-page-waits-for-the-reader', async ({+ page,+ }) => {+ await clearUserConversations(userEmail);+ /* The pins are the newest conversations, so they fill most of the first+ * page of the chats query and the list is left holding a handful of rows —+ * few enough that its last rendered row is already within the threshold+ * that asks for another page. It still sits below the fold. */+ remember(await seedPins('E2E pin', 20));+ remember(await seedChats('E2E chat', 40));++ const pages = trackChatPages(page);++ await page.goto('/c/new', { timeout: 30_000 });+ await openSidebar(page);+ await expect(pinnedRegion(page).getByTestId('convo-item').first()).toBeVisible({+ timeout: 30_000,+ });+ await waitForChatsBelowTheFold(page);++ const settled = pages.length;+ await page.waitForTimeout(3_000);+ expect(+ pages.length,+ `a short page under the pins should not fetch another, got ${pages.join(', ')}`,+ ).toBe(settled);++ for (let turn = 0; turn < 12 && pages.length === settled; turn++) {+ await scrollToBottom(page, 2);+ }+ await expect.poll(() => pages.length, { timeout: 30_000 }).toBeGreaterThan(settled);+ });+});diff --git a/e2e/specs/mock/sidebar.spec.ts b/e2e/specs/mock/sidebar.spec.tsindex 4015fcf97d..5a2e484467 100644--- a/e2e/specs/mock/sidebar.spec.ts+++ b/e2e/specs/mock/sidebar.spec.ts@@ -5,8 +5,13 @@ import { getE2EUser } from '../../setup/user';import { clearUserConversations, deleteConversations, seedConversations } from './db';import type { SeedConvo } from './db';-/** Size of the virtualized chat list grid vs. its measured container. */-const sizes = (page: Page) =>+/**+ * Width of the virtualized chat list grid vs. its measured container. The list+ * no longer owns a scroll pane: it renders at its natural height inside the+ * sidebar's single scroll surface, so its height follows the rows it holds and+ * only its width has to track the box it is measured against.+ */+const widths = (page: Page) =>page.evaluate(() => {const grid = document.querySelector<HTMLElement>('aside .ReactVirtualized__Grid');const wrap = grid?.parentElement ?? null;@@ -16,26 +21,21 @@ const sizes = (page: Page) =>grid: gridRect ? gridRect.width : -1,wrap: wrapRect ? wrapRect.width : -1,gridH: gridRect ? gridRect.height : -1,- wrapH: wrapRect ? wrapRect.height : -1,};});/**- * Polls until the grid matches its container AND the size has stopped changing+ * Polls until the grid matches its container AND the width has stopped changing* between samples — the sidebar expand/collapse animation runs for 300ms, and a* tracking-only check can match mid-animation on slow CI machines.*/-const settledSizes = async (page: Page) => {- let prev = await sizes(page);+const settledWidths = async (page: Page) => {+ let prev = await widths(page);for (let attempt = 0; attempt < 40; attempt++) {await page.waitForTimeout(350);- const next = await sizes(page);- const tracked =- next.wrap > 0 &&- next.wrapH > 0 &&- Math.abs(next.grid - next.wrap) <= 1 &&- Math.abs(next.gridH - next.wrapH) <= 1;- const stable = Math.abs(next.grid - prev.grid) <= 1 && Math.abs(next.gridH - prev.gridH) <= 1;+ const next = await widths(page);+ const tracked = next.wrap > 0 && next.gridH > 0 && Math.abs(next.grid - next.wrap) <= 1;+ const stable = Math.abs(next.grid - prev.grid) <= 1;if (tracked && stable) {return next;}@@ -45,16 +45,30 @@ const settledSizes = async (page: Page) => {};test.describe('sidebar chat list', () => {+ let sized: SeedConvo[] = [];++ test.afterEach(async () => {+ if (sized.length) {+ await deleteConversations(sized.map((convo) => convo.conversationId));+ sized = [];+ }+ });+test('chat list width tracks the sidebar through resize and collapse cycles', async ({page,}) => {test.setTimeout(60000);+ /* The grid is as tall as the rows it renders, so a list with nothing in it+ * has no box to measure: seed the rows this test measures against. */+ sized = buildSeed();+ await seedConversations(getE2EUser().email, sized);+await page.goto('/c/new', { timeout: 10000 });await expect(page.locator('aside .ReactVirtualized__Grid').first()).toBeVisible({timeout: 20000,});- const initial = await settledSizes(page);+ const initial = await settledWidths(page);const separator = page.locator('[role="separator"][aria-label="Resize sidebar"]');const sepBox = await separator.boundingBox();@@ -70,18 +84,20 @@ test.describe('sidebar chat list', () => {}await page.mouse.up();- const widened = await settledSizes(page);+ const widened = await settledWidths(page);expect(widened.grid).toBeGreaterThan(initial.grid);await page.locator('aside').getByTestId('close-sidebar-button').click();await page.locator('aside').getByTestId('open-sidebar-button').click();- const reopened = await settledSizes(page);+ const reopened = await settledWidths(page);expect(reopened.grid).toBeGreaterThan(initial.grid);+ /* A shorter viewport changes how much of the list is on screen, never how+ * wide its rows are measured. */await page.setViewportSize({ width: 1280, height: 540 });- const shrunken = await settledSizes(page);- expect(shrunken.gridH).toBeLessThan(reopened.gridH);+ const shrunken = await settledWidths(page);+ expect(Math.abs(shrunken.grid - reopened.grid)).toBeLessThanOrEqual(1);});});