:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): keep ticket thread position, add "See new messages" pill (#75390)
Luke Belton8cc07528ceb9
diff --git a/products/conversations/frontend/components/Chat/MessageList.test.tsx b/products/conversations/frontend/components/Chat/MessageList.test.tsxnew file mode 100644index 000000000000..8f34e407b60a--- /dev/null+++ b/products/conversations/frontend/components/Chat/MessageList.test.tsx@@ -0,0 +1,155 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import type { ChatMessage } from '../../types'+import { MessageList } from './MessageList'++// The real Message pulls in the tiptap-backed Editor exports for markdown and rich content; the+// behavior under test is MessageList's own scroll handling, which only needs a stand-in row.+jest.mock('./Message', () => {+ const React = jest.requireActual<typeof import('react')>('react')+ return {+ Message: ({ message }: { message: ChatMessage }) =>+ React.createElement('div', { 'data-attr': `message-${message.id}` }, message.content),+ }+})++// jsdom has no layout, so the component's "is the reader at the bottom?" arithmetic+// (scrollHeight - scrollTop - clientHeight < 120) needs fixed geometry. With these, the reader is+// pinned to the bottom above scrollTop 480 and reading history below it.+const SCROLL_HEIGHT = 1000+const CLIENT_HEIGHT = 400+const AT_BOTTOM = 600+const SCROLLED_UP = 100++const PILL = 'See new messages'++function message(id: string, createdAt: string): ChatMessage {+ return {+ id,+ content: `Message ${id}`,+ authorType: 'customer',+ authorName: 'Customer',+ createdAt,+ }+}++const FIRST = message('1', '2026-01-01T00:00:00Z')+const SECOND = message('2', '2026-01-01T00:01:00Z')+const OLDER = message('0', '2025-12-31T00:00:00Z')++function scrollContainer(): HTMLElement {+ return screen.getByTestId('message-list-scroll')+}++/** Move the reader and fire the scroll event the component listens for. */+function scrollTo(top: number): void {+ const container = scrollContainer()+ container.scrollTop = top+ fireEvent.scroll(container)+}++let scrollToSpy: jest.Mock++describe('MessageList', () => {+ beforeEach(() => {+ scrollToSpy = jest.fn()+ Element.prototype.scrollTo = scrollToSpy+ Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {+ configurable: true,+ get: () => SCROLL_HEIGHT,+ })+ Object.defineProperty(HTMLElement.prototype, 'clientHeight', {+ configurable: true,+ get: () => CLIENT_HEIGHT,+ })+ })++ afterEach(() => {+ cleanup()+ })++ it('opens the thread at the latest message when content first loads', () => {+ render(<MessageList messages={[FIRST]} messagesLoading={false} />)++ expect(scrollToSpy).toHaveBeenCalledWith({ top: SCROLL_HEIGHT, behavior: 'instant' })+ expect(screen.queryByText(PILL)).not.toBeInTheDocument()+ })++ it('follows the tail when a new message arrives while the reader is at the bottom', () => {+ const { rerender } = render(<MessageList messages={[FIRST]} messagesLoading={false} />)+ scrollTo(AT_BOTTOM)+ scrollToSpy.mockClear()++ rerender(<MessageList messages={[FIRST, SECOND]} messagesLoading={false} />)++ expect(scrollToSpy).toHaveBeenCalledWith({ top: SCROLL_HEIGHT, behavior: 'smooth' })+ expect(screen.queryByText(PILL)).not.toBeInTheDocument()+ })++ it('holds position and offers the pill when a message arrives after the reader scrolls up', () => {+ const { rerender } = render(<MessageList messages={[FIRST]} messagesLoading={false} />)+ scrollTo(SCROLLED_UP)+ scrollToSpy.mockClear()++ rerender(<MessageList messages={[FIRST, SECOND]} messagesLoading={false} />)++ expect(scrollToSpy).not.toHaveBeenCalled()+ expect(screen.getByText(PILL)).toBeInTheDocument()+ })++ // The regression this PR exists for: agent reports load on their own async request, so one can+ // land long after the messages have settled and must not yank a reader out of history.+ it('holds position and offers the pill when an agent report arrives after the reader scrolls up', () => {+ const { rerender } = render(<MessageList messages={[FIRST]} messagesLoading={false} extras={[]} />)+ scrollTo(SCROLLED_UP)+ scrollToSpy.mockClear()++ rerender(+ <MessageList+ messages={[FIRST]}+ messagesLoading={false}+ extras={[{ at: '2026-01-01T00:02:00Z', element: <div key="report">Agent report</div> }]}+ />+ )++ expect(scrollToSpy).not.toHaveBeenCalled()+ expect(screen.getByText(PILL)).toBeInTheDocument()+ })++ it('does not offer the pill when older messages are prepended', () => {+ const { rerender } = render(<MessageList messages={[FIRST]} messagesLoading={false} />)+ scrollTo(SCROLLED_UP)+ scrollToSpy.mockClear()++ // "Load older" grows messages.length but leaves the newest message unchanged.+ rerender(<MessageList messages={[OLDER, FIRST]} messagesLoading={false} />)++ expect(scrollToSpy).not.toHaveBeenCalled()+ expect(screen.queryByText(PILL)).not.toBeInTheDocument()+ })++ it('jumps to the latest and dismisses the pill when it is clicked', () => {+ const { rerender } = render(<MessageList messages={[FIRST]} messagesLoading={false} />)+ scrollTo(SCROLLED_UP)+ rerender(<MessageList messages={[FIRST, SECOND]} messagesLoading={false} />)+ scrollToSpy.mockClear()++ fireEvent.click(screen.getByText(PILL))++ expect(scrollToSpy).toHaveBeenCalledWith({ top: SCROLL_HEIGHT, behavior: 'smooth' })+ expect(screen.queryByText(PILL)).not.toBeInTheDocument()+ })++ it('dismisses the pill once the reader scrolls back to the bottom themselves', () => {+ const { rerender } = render(<MessageList messages={[FIRST]} messagesLoading={false} />)+ scrollTo(SCROLLED_UP)+ rerender(<MessageList messages={[FIRST, SECOND]} messagesLoading={false} />)+ expect(screen.getByText(PILL)).toBeInTheDocument()++ scrollTo(AT_BOTTOM)++ expect(screen.queryByText(PILL)).not.toBeInTheDocument()+ })+})diff --git a/products/conversations/frontend/components/Chat/MessageList.tsx b/products/conversations/frontend/components/Chat/MessageList.tsxindex 5351dfa127b5..9efd2eaf0831 100644--- a/products/conversations/frontend/components/Chat/MessageList.tsx+++ b/products/conversations/frontend/components/Chat/MessageList.tsx@@ -1,6 +1,8 @@-import { useEffect, useRef } from 'react'+import { useEffect, useRef, useState } from 'react'-import { Spinner } from '@posthog/lemon-ui'+import { LemonButton, Spinner } from '@posthog/lemon-ui'++import { IconArrowDown } from 'lib/lemon-ui/icons'import type { AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'import { Message } from './Message'@@ -63,26 +65,96 @@ export function MessageList({}: MessageListProps): JSX.Element {const messagesEndRef = useRef<HTMLDivElement>(null)const containerRef = useRef<HTMLDivElement>(null)+ // Whether the reader is at (or near) the bottom of the thread. Starts true so+ // the thread opens on its latest message; scrolling up clears it and scrolling+ // back down restores it. Auto-scroll is gated on this so late-arriving content+ // — notably a self-driving agent report, which loads on its own async request+ // separate from the polled messages — never yanks a reader who has scrolled up+ // into history back down to the bottom.+ const pinnedToBottomRef = useRef(true)+ // Latches once the thread has been opened at the bottom, so that initial jump+ // happens exactly once per loaded thread rather than on every content change.+ const openedAtBottomRef = useRef(false)+ // Raised when new tail content lands while the reader has scrolled up into+ // history. Drives the "See new messages" pill so they can drop to the latest+ // on their own terms instead of being yanked down.+ const [newContentBelow, setNewContentBelow] = useState(false)+ // The newest message id, so the effect can tell a real tail append (or a new+ // agent report) from an older-page prepend — "Load older" grows messages.length+ // too, but must never raise the pill.+ const lastMessageId = messages.length > 0 ? messages[messages.length - 1].id : null+ const prevLastMessageIdRef = useRef<string | null>(null)+ const prevExtrasCountRef = useRef(0)- const scrollToBottom = (): void => {- if (containerRef.current && messagesEndRef.current) {- containerRef.current.scrollTo({- top: containerRef.current.scrollHeight,- behavior: 'smooth',- })+ const scrollToBottom = (behavior: ScrollBehavior = 'smooth'): void => {+ const container = containerRef.current+ if (container) {+ container.scrollTo({ top: container.scrollHeight, behavior })}}+ const jumpToLatest = (): void => {+ pinnedToBottomRef.current = true+ setNewContentBelow(false)+ scrollToBottom()+ }+useEffect(() => {- if (messages.length > 0 || extras.length > 0) {+ // No content yet: reset the latch and tail tracking so a freshly loaded+ // thread opens at the bottom again (e.g. after switching tickets).+ if (messages.length === 0 && extras.length === 0) {+ openedAtBottomRef.current = false+ prevLastMessageIdRef.current = null+ prevExtrasCountRef.current = 0+ setNewContentBelow(false)+ return+ }++ const prevLastMessageId = prevLastMessageIdRef.current+ const prevExtrasCount = prevExtrasCountRef.current+ prevLastMessageIdRef.current = lastMessageId+ prevExtrasCountRef.current = extras.length++ // Open at the latest message the first time content lands, instantly.+ if (!openedAtBottomRef.current) {+ openedAtBottomRef.current = true+ pinnedToBottomRef.current = true+ scrollToBottom('instant')+ return+ }++ // Only a tail append (newest message id advanced) or a new extra (agent+ // report) counts as new content below. Prepending older pages changes+ // messages[0], not the last id, so "Load older" never raises the pill.+ const tailGrew = lastMessageId !== prevLastMessageId || extras.length > prevExtrasCount+ if (!tailGrew) {+ return+ }++ // Follow the tail when the reader is already there; otherwise hold their+ // position and raise the pill so they can drop to the latest themselves.+ if (pinnedToBottomRef.current) {scrollToBottom()+ } else {+ setNewContentBelow(true)}- // Extras land in the same stream, so one arriving has to scroll like a message does.- }, [messages.length, extras.length])+ }, [lastMessageId, extras.length, messages.length])const handleScroll = (): void => {const container = containerRef.current- if (!container || olderMessagesLoading || !hasMoreMessages || !onLoadOlderMessages) {+ if (!container) {+ return+ }++ // Track whether the reader is pinned to the bottom. The window is generous+ // so a smooth auto-scroll still in flight keeps counting as pinned.+ pinnedToBottomRef.current = container.scrollHeight - container.scrollTop - container.clientHeight < 120+ // Returning to the bottom (by the pill or by hand) clears the pill.+ if (pinnedToBottomRef.current) {+ setNewContentBelow(false)+ }++ if (olderMessagesLoading || !hasMoreMessages || !onLoadOlderMessages) {return}@@ -154,28 +226,50 @@ export function MessageList({.map(({ element }) => element)return (- <div- ref={containerRef}- onScroll={handleScroll}- className={`flex-1 overflow-y-auto space-y-1.5 ${className}`}- style={{ minHeight, maxHeight }}- >- {olderMessagesLoading && (- <div className="flex items-center justify-center py-2">- <Spinner className="text-sm" />- </div>- )}- {messagesLoading && messages.length === 0 ? (- <div className="flex items-center justify-center h-full">- <Spinner />+ // The wrapper is the component root, so it keeps the contract the scroll container used to+ // hold: it takes the caller's className and the height bounds, and stays the flex child+ // callers lay out against. Without that, a caller's spacing (e.g. `mb-3`) would land inside+ // the wrapper and stop separating the thread from whatever follows it.+ <div className={`relative flex flex-col flex-1 ${className}`} style={{ minHeight, maxHeight }}>+ <div+ ref={containerRef}+ onScroll={handleScroll}+ data-attr="message-list-scroll"+ className="flex-1 min-h-0 overflow-y-auto space-y-1.5"+ >+ {olderMessagesLoading && (+ <div className="flex items-center justify-center py-2">+ <Spinner className="text-sm" />+ </div>+ )}+ {messagesLoading && messages.length === 0 ? (+ <div className="flex items-center justify-center h-full">+ <Spinner />+ </div>+ ) : messages.length === 0 ? (+ <div className="flex items-center justify-center h-full text-muted-alt text-sm">{emptyMessage}</div>+ ) : (+ <>+ {timeline}+ <div ref={messagesEndRef} />+ </>+ )}+ </div>+ {/* Sits over the bottom of the thread, not in the scroll flow, so it stays put as a+ jump-to-latest affordance while the reader is up in history. The strip ignores+ pointer events so only the pill itself is clickable. */}+ {newContentBelow && (+ <div className="absolute inset-x-0 bottom-2 flex justify-center pointer-events-none">+ <LemonButton+ type="primary"+ size="small"+ icon={<IconArrowDown />}+ onClick={jumpToLatest}+ className="pointer-events-auto rounded-full shadow-md"+ >+ See new messages+ </LemonButton></div>- ) : messages.length === 0 ? (- <div className="flex items-center justify-center h-full text-muted-alt text-sm">{emptyMessage}</div>- ) : (- <>- {timeline}- <div ref={messagesEndRef} />- </>)}</div>)