An open source design system that's fully customizable and agent ready
TypeScript
fix(Chat): use callback ref for content observation (#2282) (#2285)
Cindy Zhang9ed061d807da
diff --git a/apps/storybook/stories/ChatAutoScroll.stories.tsx b/apps/storybook/stories/ChatAutoScroll.stories.tsxnew file mode 100644index 0000000000..a62912e2ea--- /dev/null+++ b/apps/storybook/stories/ChatAutoScroll.stories.tsx@@ -0,0 +1,843 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Demonstrates the auto-scroll behavior difference between streaming text+ * and discrete block additions (tool calls, custom elements).+ *+ * Issue: https://github.com/facebookexperimental/xds/issues/2282+ *+ * The auto-scroll system (useXDSChatStreamScroll + useXDSChatNewMessages)+ * relies on ResizeObserver detecting content height changes. This story+ * isolates three scenarios:+ *+ * 1. Streaming text — continuous height growth, auto-scroll follows ✓+ * 2. Tool calls — discrete height jumps, auto-scroll may miss ✗+ * 3. Large custom elements — single large height change, may miss ✗+ */++import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSChatLayout,+ XDSChatMessageList,+ XDSChatMessage,+ XDSChatToolCalls,+ XDSChatComposer,+ type XDSChatToolCallItem,+} from '@xds/core/Chat';+import {XDSMarkdown} from '@xds/core/Markdown';+import {XDSButton} from '@xds/core/Button';+import {XDSText} from '@xds/core/Text';+import {XDSCodeBlock} from '@xds/core/CodeBlock';+import {XDSBadge} from '@xds/core/Badge';+import {useState, useCallback, useRef} from 'react';+import * as stylex from '@stylexjs/stylex';++const meta: Meta = {+ title: 'Core/Chat/AutoScroll',+ tags: ['autodocs'],+ parameters: {layout: 'fullscreen'},+};+export default meta;++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ wrapper: {+ height: '100vh',+ display: 'flex',+ flexDirection: 'column' as const,+ },+ controls: {+ display: 'flex',+ gap: 8,+ padding: 12,+ borderBottom: '1px solid #e5e5e5',+ flexWrap: 'wrap' as const,+ alignItems: 'center',+ },+ statusPill: {+ marginInlineStart: 'auto',+ display: 'flex',+ alignItems: 'center',+ gap: 6,+ },+ customElement: {+ padding: 16,+ borderRadius: 12,+ border: '1px solid #e5e7eb',+ background: '#f9fafb',+ },+ customElementInner: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ height: 200,+ borderRadius: 8,+ background: '#f3f4f6',+ },+});++// =============================================================================+// Helpers+// =============================================================================++const STREAMING_TEXT = `Let me analyze this codebase for you. I'll start by looking at the project structure and understanding the architecture.++The project uses a **monorepo** structure with the following key directories:++- \`packages/core/\` — Published core components and utilities+- \`packages/cli/\` — CLI tooling for scaffolding+- \`apps/storybook/\` — Storybook for component development+- \`apps/sandbox/\` — Sandbox testing app++Looking at the architecture more closely, the system follows a **plugin-based pattern** where components are composed through a unified swizzle system. This means any internal primitive can be overridden at any level.++The auto-scroll system uses \`useXDSChatStreamScroll\` which provides spring-based scroll-to-bottom with lock/unlock behavior:++\`\`\`tsx+const scroll = useXDSChatStreamScroll({scrollRef});+// scroll.isLocked — auto-following content+// scroll.scrollIfLocked() — call on resize+\`\`\`++This is paired with \`useXDSChatNewMessages\` which observes the content element via ResizeObserver and calls \`scrollIfLocked()\` on every height change.++The key question is: **does the ResizeObserver fire reliably for all types of content additions?**`;++const TOOL_CALLS_SEQUENCE: XDSChatToolCallItem[][] = [+ [+ {+ key: '1',+ name: 'read',+ target: 'packages/core/src/Chat/useXDSChatStreamScroll.ts',+ status: 'complete',+ duration: '42ms',+ node: 'xds',+ },+ ],+ [+ {+ key: '2',+ name: 'bash',+ target: 'yarn test --filter Chat',+ status: 'complete',+ duration: '4.2s',+ node: 'xds',+ },+ ],+ [+ {+ key: '3',+ name: 'edit',+ target: 'XDSChatLayout.tsx',+ status: 'complete',+ duration: '95ms',+ node: 'xds',+ additions: 12,+ deletions: 3,+ resultDetail: (+ <XDSCodeBlock+ code={`// Added MutationObserver supplement\nconst observer = new MutationObserver(() => {\n scrollIfLocked();\n});\nobserver.observe(contentEl, { childList: true, subtree: true });`}+ language="typescript"+ />+ ),+ },+ ],+ [+ {+ key: '4',+ name: 'bash',+ target: 'yarn test',+ status: 'complete',+ duration: '8.1s',+ node: 'xds',+ resultDetail: (+ <XDSCodeBlock+ code={`$ yarn test\n✓ 142 tests passed (18 suites)\n\nTest Suites: 18 passed, 18 total\nTests: 142 passed, 142 total\nTime: 8.1s`}+ language="bash"+ />+ ),+ },+ ],+ [+ {+ key: '5',+ name: 'read',+ target: 'packages/core/src/Chat/useXDSChatNewMessages.ts',+ status: 'complete',+ duration: '38ms',+ node: 'xds',+ },+ ],+];++// =============================================================================+// Type for messages+// =============================================================================++type DemoMessage = {+ id: number;+ role: 'user' | 'assistant';+ text: string;+ toolCalls?: XDSChatToolCallItem[];+ customElement?: React.ReactNode;+ isStreaming?: boolean;+};++// =============================================================================+// Stories+// =============================================================================++/**+ * Demonstrates the auto-scroll issue: streaming text scrolls correctly,+ * but tool calls and custom elements may not trigger auto-scroll.+ *+ * Use the control buttons to add different content types and observe+ * whether the chat auto-scrolls to keep new content visible.+ */+export const ScrollBehaviorComparison: StoryObj = {+ name: 'Scroll Behavior Comparison',+ render: () => {+ const [messages, setMessages] = useState<DemoMessage[]>([+ {+ id: 1,+ role: 'user',+ text: 'Can you analyze the auto-scroll system and fix the issue with tool calls?',+ },+ {+ id: 2,+ role: 'assistant',+ text: "Sure, I'll look into the auto-scroll behavior. Let me start by reading the relevant files.\n\nThe scroll system uses `useXDSChatStreamScroll` for spring-based scroll tracking and `useXDSChatNewMessages` for content observation.",+ },+ {id: 3, role: 'user', text: 'Great, show me what you find.'},+ ]);+ const [isStreaming, setIsStreaming] = useState(false);+ const streamRef = useRef<ReturnType<typeof setInterval>>(undefined);+ const toolCallIndex = useRef(0);++ // --- Stream text (should auto-scroll) ---+ const handleStreamText = useCallback(() => {+ const msgId = Date.now();+ setIsStreaming(true);++ setMessages(prev => [+ ...prev,+ {id: msgId, role: 'assistant', text: '', isStreaming: true},+ ]);++ let charIdx = 0;+ streamRef.current = setInterval(() => {+ charIdx += 2 + Math.floor(Math.random() * 4);+ if (charIdx >= STREAMING_TEXT.length) {+ clearInterval(streamRef.current);+ setMessages(prev =>+ prev.map(m =>+ m.id === msgId+ ? {...m, text: STREAMING_TEXT, isStreaming: false}+ : m,+ ),+ );+ setIsStreaming(false);+ return;+ }+ setMessages(prev =>+ prev.map(m =>+ m.id === msgId ? {...m, text: STREAMING_TEXT.slice(0, charIdx)} : m,+ ),+ );+ }, 25);+ }, []);++ // --- Add tool calls one at a time (may fail to auto-scroll) ---+ const handleAddToolCall = useCallback(() => {+ const tools =+ TOOL_CALLS_SEQUENCE[toolCallIndex.current % TOOL_CALLS_SEQUENCE.length];+ toolCallIndex.current++;++ const msgId = Date.now();+ // First add with 'running' status+ setMessages(prev => [+ ...prev,+ {+ id: msgId,+ role: 'assistant',+ text: '',+ toolCalls: tools?.map(tc => ({+ ...tc,+ status: 'running' as const,+ duration: undefined,+ })),+ },+ ]);++ // After a delay, mark as complete+ setTimeout(() => {+ setMessages(prev =>+ prev.map(m => (m.id === msgId ? {...m, toolCalls: tools} : m)),+ );+ }, 1200);+ }, []);++ // --- Add batch of tool calls at once (most likely to miss scroll) ---+ const handleBatchToolCalls = useCallback(() => {+ const msgId = Date.now();+ const allCalls = TOOL_CALLS_SEQUENCE.flat().map((tc, i) => ({+ ...tc,+ key: `batch-${i}`,+ }));++ setMessages(prev => [+ ...prev,+ {+ id: msgId,+ role: 'assistant',+ text: 'Here are the results from my investigation:',+ toolCalls: allCalls,+ },+ ]);+ }, []);++ // --- Add a large custom element (simulates embedded widget) ---+ const handleAddCustomElement = useCallback(() => {+ const msgId = Date.now();+ setMessages(prev => [+ ...prev,+ {+ id: msgId,+ role: 'assistant',+ text: '',+ customElement: (+ <div {...stylex.props(styles.customElement)}>+ <XDSText type="label" weight="bold">+ Architecture Diagram+ </XDSText>+ <div {...stylex.props(styles.customElementInner)}>+ <XDSText type="body" color="secondary">+ 📊 Embedded visualization (200px tall custom element)+ </XDSText>+ </div>+ <XDSCodeBlock+ code={`┌─────────────────────┐\n│ useXDSChatStream │\n│ Scroll │\n├─────────────────────┤\n│ ResizeObserver ──► │──► scrollIfLocked()\n│ (content height) │\n└─────────────────────┘\n ▲\n │ fires on height change\n │\n┌─────────────────────┐\n│ useXDSChatNew │\n│ Messages │\n├─────────────────────┤\n│ observeResize() ──► │──► onResize callback\n│ (shared observer) │\n└─────────────────────┘`}+ language="text"+ />+ </div>+ ),+ },+ ]);+ }, []);++ // --- Reset ---+ const handleReset = useCallback(() => {+ clearInterval(streamRef.current);+ setIsStreaming(false);+ toolCallIndex.current = 0;+ setMessages([+ {+ id: 1,+ role: 'user',+ text: 'Can you analyze the auto-scroll system and fix the issue with tool calls?',+ },+ {+ id: 2,+ role: 'assistant',+ text: "Sure, I'll look into the auto-scroll behavior. Let me start by reading the relevant files.\n\nThe scroll system uses `useXDSChatStreamScroll` for spring-based scroll tracking and `useXDSChatNewMessages` for content observation.",+ },+ {id: 3, role: 'user', text: 'Great, show me what you find.'},+ ]);+ }, []);++ return (+ <div {...stylex.props(styles.wrapper)}>+ {/* Control bar */}+ <div {...stylex.props(styles.controls)}>+ <XDSButton+ label="Stream Text (works ✓)"+ variant="primary"+ size="sm"+ onClick={handleStreamText}+ isDisabled={isStreaming}+ />+ <XDSButton+ label="Add Tool Call (may fail ✗)"+ variant="secondary"+ size="sm"+ onClick={handleAddToolCall}+ />+ <XDSButton+ label="Batch Tool Calls (likely fails ✗)"+ variant="secondary"+ size="sm"+ onClick={handleBatchToolCalls}+ />+ <XDSButton+ label="Add Custom Element (may fail ✗)"+ variant="secondary"+ size="sm"+ onClick={handleAddCustomElement}+ />+ <XDSButton+ label="Reset"+ variant="ghost"+ size="sm"+ onClick={handleReset}+ />+ <div {...stylex.props(styles.statusPill)}>+ <XDSBadge+ variant={isStreaming ? 'green' : 'neutral'}+ label={isStreaming ? 'Streaming' : 'Idle'}+ />+ </div>+ </div>++ {/* Chat area */}+ <XDSChatLayout+ composer={+ <XDSChatComposer+ onSubmit={() => {}}+ placeholder="Observe auto-scroll behavior above..."+ isStreaming={isStreaming}+ />+ }>+ <XDSChatMessageList>+ {messages.map(msg => (+ <XDSChatMessage key={msg.id} sender={msg.role}>+ {msg.text && (+ <XDSMarkdown density="compact">{msg.text}</XDSMarkdown>+ )}+ {msg.toolCalls && msg.toolCalls.length > 0 && (+ <XDSChatToolCalls calls={msg.toolCalls} />+ )}+ {msg.customElement}+ </XDSChatMessage>+ ))}+ </XDSChatMessageList>+ </XDSChatLayout>+ </div>+ );+ },+};++/**+ * Rapid tool call additions — fires 5 tool calls every 500ms to stress-test+ * the ResizeObserver + scrollIfLocked pathway.+ */+export const RapidToolCalls: StoryObj = {+ name: 'Rapid Tool Calls',+ render: () => {+ const [messages, setMessages] = useState<DemoMessage[]>([+ {+ id: 1,+ role: 'user',+ text: 'Run the full test suite across all packages.',+ },+ ]);+ const [isRunning, setIsRunning] = useState(false);+ const intervalRef = useRef<ReturnType<typeof setInterval>>(undefined);+ const counterRef = useRef(0);++ const handleStart = useCallback(() => {+ setIsRunning(true);+ counterRef.current = 0;++ intervalRef.current = setInterval(() => {+ counterRef.current++;+ if (counterRef.current > 10) {+ clearInterval(intervalRef.current);+ setIsRunning(false);+ return;+ }++ const msgId = Date.now() + counterRef.current;+ const toolNames = ['read', 'bash', 'edit', 'ipython', 'show'];+ const targets = [+ 'XDSButton.test.tsx',+ 'yarn test --filter=Button',+ 'XDSButton.tsx +8 -2',+ 'analyze_coverage()',+ 'coverage-report.html',+ ];+ const idx = (counterRef.current - 1) % toolNames.length;++ setMessages(prev => [+ ...prev,+ {+ id: msgId,+ role: 'assistant',+ text: '',+ toolCalls: [+ {+ key: String(msgId),+ name: toolNames[idx] ?? 'read',+ target: targets[idx],+ status: 'running',+ node: 'xds',+ },+ ],+ },+ ]);++ // Mark complete after 300ms+ setTimeout(() => {+ setMessages(prev =>+ prev.map(m =>+ m.id === msgId+ ? {+ ...m,+ toolCalls: [+ {+ key: String(msgId),+ name: toolNames[idx] ?? 'read',+ target: targets[idx],+ status: 'complete' as const,+ duration: `${(Math.random() * 3 + 0.1).toFixed(1)}s`,+ node: 'xds',+ },+ ],+ }+ : m,+ ),+ );+ }, 300);+ }, 500);+ }, []);++ const handleStop = useCallback(() => {+ clearInterval(intervalRef.current);+ setIsRunning(false);+ }, []);++ const handleReset = useCallback(() => {+ clearInterval(intervalRef.current);+ setIsRunning(false);+ counterRef.current = 0;+ setMessages([+ {+ id: 1,+ role: 'user',+ text: 'Run the full test suite across all packages.',+ },+ ]);+ }, []);++ return (+ <div {...stylex.props(styles.wrapper)}>+ <div {...stylex.props(styles.controls)}>+ <XDSButton+ label={isRunning ? 'Running...' : 'Start Rapid Tool Calls'}+ variant="primary"+ size="sm"+ onClick={handleStart}+ isDisabled={isRunning}+ />+ <XDSButton+ label="Stop"+ variant="destructive"+ size="sm"+ onClick={handleStop}+ isDisabled={!isRunning}+ />+ <XDSButton+ label="Reset"+ variant="ghost"+ size="sm"+ onClick={handleReset}+ />+ <div {...stylex.props(styles.statusPill)}>+ <XDSBadge+ variant={isRunning ? 'yellow' : 'neutral'}+ label={+ isRunning+ ? `Tool call ${counterRef.current}/10`+ : `${messages.length - 1} messages`+ }+ />+ </div>+ </div>++ <XDSChatLayout+ composer={+ <XDSChatComposer+ onSubmit={() => {}}+ placeholder="Watch scroll behavior..."+ />+ }>+ <XDSChatMessageList>+ {messages.map(msg => (+ <XDSChatMessage key={msg.id} sender={msg.role}>+ {msg.text && (+ <XDSMarkdown density="compact">{msg.text}</XDSMarkdown>+ )}+ {msg.toolCalls && msg.toolCalls.length > 0 && (+ <XDSChatToolCalls calls={msg.toolCalls} />+ )}+ </XDSChatMessage>+ ))}+ </XDSChatMessageList>+ </XDSChatLayout>+ </div>+ );+ },+};++/**+ * Mixed content — alternates between streaming text and tool call blocks,+ * showing the transition points where scroll may break.+ */+export const MixedStreamAndTools: StoryObj = {+ name: 'Mixed Stream + Tools',+ render: () => {+ const [messages, setMessages] = useState<DemoMessage[]>([+ {id: 1, role: 'user', text: 'Fix the focus ring and run the tests.'},+ ]);+ const [phase, setPhase] = useState<'idle' | 'streaming' | 'tools' | 'done'>(+ 'idle',+ );+ const streamRef = useRef<ReturnType<typeof setInterval>>(undefined);++ const handleRun = useCallback(() => {+ setPhase('streaming');+ const msgId = Date.now();+ const introText =+ "Let me look at the Button component's focus styles and fix the ring.\n\nI can see the issue — the focus ring uses a hardcoded color instead of the theme token. Let me fix that and run the tests.";++ setMessages(prev => [+ ...prev,+ {id: msgId, role: 'assistant', text: '', isStreaming: true},+ ]);++ let i = 0;+ streamRef.current = setInterval(() => {+ i += 3 + Math.floor(Math.random() * 4);+ if (i >= introText.length) {+ clearInterval(streamRef.current);+ setMessages(prev =>+ prev.map(m =>+ m.id === msgId ? {...m, text: introText, isStreaming: false} : m,+ ),+ );++ // Transition to tool calls+ setPhase('tools');+ setTimeout(() => {+ const toolMsgId = Date.now();+ setMessages(prev => [+ ...prev,+ {+ id: toolMsgId,+ role: 'assistant',+ text: '',+ toolCalls: [+ {+ key: '1',+ name: 'edit',+ target: 'XDSButton.tsx',+ status: 'running',+ node: 'xds',+ },+ ],+ },+ ]);++ setTimeout(() => {+ setMessages(prev =>+ prev.map(m =>+ m.id === toolMsgId+ ? {+ ...m,+ toolCalls: [+ {+ key: '1',+ name: 'edit',+ target: 'XDSButton.tsx',+ status: 'complete',+ duration: '92ms',+ node: 'xds',+ additions: 4,+ deletions: 2,+ resultDetail: (+ <XDSCodeBlock+ code={`- outline: 2px solid blue;\n+ outline: 2px solid var(--color-ring-focus);\n+ outline-offset: 2px;`}+ language="diff"+ />+ ),+ },+ ],+ }+ : m,+ ),+ );++ // Second tool call+ setTimeout(() => {+ const testMsgId = Date.now();+ setMessages(prev => [+ ...prev,+ {+ id: testMsgId,+ role: 'assistant',+ text: '',+ toolCalls: [+ {+ key: '2',+ name: 'bash',+ target: 'yarn test --filter Button',+ status: 'running',+ node: 'xds',+ },+ ],+ },+ ]);++ setTimeout(() => {+ setMessages(prev =>+ prev.map(m =>+ m.id === testMsgId+ ? {+ ...m,+ toolCalls: [+ {+ key: '2',+ name: 'bash',+ target: 'yarn test --filter Button',+ status: 'complete',+ duration: '3.8s',+ node: 'xds',+ resultDetail: (+ <XDSCodeBlock+ code={`✓ 24 tests passed\n\nTest Suites: 3 passed, 3 total\nTests: 24 passed, 24 total`}+ language="bash"+ />+ ),+ },+ ],+ }+ : m,+ ),+ );++ // Final streaming summary+ setTimeout(() => {+ const summaryId = Date.now();+ const summaryText =+ 'Done! The focus ring now uses the theme token `var(--color-ring-focus)` with a 2px offset. All 24 tests pass.\n\nThe fix ensures the ring adapts to different themes automatically — no more hardcoded blue.';+ setMessages(prev => [+ ...prev,+ {+ id: summaryId,+ role: 'assistant',+ text: '',+ isStreaming: true,+ },+ ]);++ let j = 0;+ streamRef.current = setInterval(() => {+ j += 3 + Math.floor(Math.random() * 4);+ if (j >= summaryText.length) {+ clearInterval(streamRef.current);+ setMessages(prev =>+ prev.map(m =>+ m.id === summaryId+ ? {...m, text: summaryText, isStreaming: false}+ : m,+ ),+ );+ setPhase('done');+ return;+ }+ setMessages(prev =>+ prev.map(m =>+ m.id === summaryId+ ? {...m, text: summaryText.slice(0, j)}+ : m,+ ),+ );+ }, 25);+ }, 600);+ }, 2000);+ }, 800);+ }, 1500);+ }, 500);++ return;+ }+ setMessages(prev =>+ prev.map(m =>+ m.id === msgId ? {...m, text: introText.slice(0, i)} : m,+ ),+ );+ }, 25);+ }, []);++ const handleReset = useCallback(() => {+ clearInterval(streamRef.current);+ setPhase('idle');+ setMessages([+ {id: 1, role: 'user', text: 'Fix the focus ring and run the tests.'},+ ]);+ }, []);++ return (+ <div {...stylex.props(styles.wrapper)}>+ <div {...stylex.props(styles.controls)}>+ <XDSButton+ label="Run Full Sequence"+ variant="primary"+ size="sm"+ onClick={handleRun}+ isDisabled={phase !== 'idle' && phase !== 'done'}+ />+ <XDSButton+ label="Reset"+ variant="ghost"+ size="sm"+ onClick={handleReset}+ />+ <div {...stylex.props(styles.statusPill)}>+ <XDSBadge+ variant={+ phase === 'streaming'+ ? 'green'+ : phase === 'tools'+ ? 'yellow'+ : 'neutral'+ }+ label={+ phase === 'idle'+ ? 'Ready'+ : phase === 'streaming'+ ? 'Streaming text...'+ : phase === 'tools'+ ? 'Adding tool calls...'+ : 'Complete'+ }+ />+ </div>+ </div>++ <XDSChatLayout+ composer={+ <XDSChatComposer+ onSubmit={() => {}}+ placeholder="Watch the transition from streaming → tool calls..."+ />+ }>+ <XDSChatMessageList>+ {messages.map(msg => (+ <XDSChatMessage key={msg.id} sender={msg.role}>+ {msg.text && (+ <XDSMarkdown density="compact">{msg.text}</XDSMarkdown>+ )}+ {msg.toolCalls && msg.toolCalls.length > 0 && (+ <XDSChatToolCalls calls={msg.toolCalls} />+ )}+ </XDSChatMessage>+ ))}+ </XDSChatMessageList>+ </XDSChatLayout>+ </div>+ );+ },+};diff --git a/packages/core/src/Chat/XDSChatLayout.tsx b/packages/core/src/Chat/XDSChatLayout.tsxindex 0c19677c16..6b2775c6b8 100644--- a/packages/core/src/Chat/XDSChatLayout.tsx+++ b/packages/core/src/Chat/XDSChatLayout.tsx@@ -281,8 +281,6 @@ export function XDSChatLayout({}: XDSChatLayoutProps) {const rootRef = useRef<HTMLDivElement>(null);- const contentRef = useRef<HTMLElement>(null);-const scrollContainerRef =externalScrollRef ?? (rootRef as React.RefObject<HTMLElement | null>);const isSelfScrolling = !externalScrollRef;@@ -292,7 +290,6 @@ export function XDSChatLayout({// --- Default scroll behavior ---const scroll = useXDSChatStreamScroll({scrollRef: scrollContainerRef});const newMsgs = useXDSChatNewMessages({- contentRef,isLocked: scroll.isLocked,onResize: scroll.scrollIfLocked,});@@ -308,15 +305,10 @@ export function XDSChatLayout({/>);- // --- Content ref callback for message list ---- const setContentRef = useCallback((el: HTMLElement | null) => {- contentRef.current = el;- }, []);-// --- Layout context ---const layoutContext = useMemo(- () => ({scrollContainerRef, contentRef: setContentRef}),- [scrollContainerRef, setContentRef],+ () => ({scrollContainerRef, contentRef: newMsgs.contentRef}),+ [scrollContainerRef, newMsgs.contentRef],);// --- Density observer ---diff --git a/packages/core/src/Chat/useXDSChatNewMessages.test.tsx b/packages/core/src/Chat/useXDSChatNewMessages.test.tsxnew file mode 100644index 0000000000..ba471c4ca7--- /dev/null+++ b/packages/core/src/Chat/useXDSChatNewMessages.test.tsx@@ -0,0 +1,209 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {render, act} from '@testing-library/react';+import {useState} from 'react';+import {XDSChatLayout} from './XDSChatLayout';+import {XDSChatMessageList} from './XDSChatMessageList';+import {XDSChatMessage} from './XDSChatMessage';+import {XDSChatMessageBubble} from './XDSChatMessageBubble';+import {useXDSChatNewMessages} from './useXDSChatNewMessages';++// ---------------------------------------------------------------------------+// Test infrastructure: track ResizeObserver observations+// ---------------------------------------------------------------------------++type ObserverEntry = {element: Element; callback: ResizeObserverCallback};+let activeObservations: ObserverEntry[] = [];++class FakeResizeObserver {+ callback: ResizeObserverCallback;+ observed = new Set<Element>();++ constructor(cb: ResizeObserverCallback) {+ this.callback = cb;+ }++ observe(el: Element) {+ this.observed.add(el);+ activeObservations.push({element: el, callback: this.callback});+ this.callback([{target: el} as ResizeObserverEntry], this);+ }++ unobserve(el: Element) {+ this.observed.delete(el);+ activeObservations = activeObservations.filter(o => o.element !== el);+ }++ disconnect() {+ for (const el of this.observed) {+ activeObservations = activeObservations.filter(o => o.element !== el);+ }+ this.observed.clear();+ }+}++beforeEach(() => {+ activeObservations = [];+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe('useXDSChatNewMessages — callback ref (issue #2282)', () => {+ it('attaches observer when element is provided immediately', () => {+ const onResize = vi.fn();++ function TestHarness() {+ const {contentRef} = useXDSChatNewMessages({isLocked: true, onResize});+ return (+ <div ref={contentRef} data-testid="content">+ <div className="xds-chat-message">msg</div>+ </div>+ );+ }++ render(<TestHarness />);+ // observeResize fires initial callback → onResize called+ expect(onResize).toHaveBeenCalled();+ });++ it('attaches observer when element mounts late (callback ref)', () => {+ const onResize = vi.fn();++ function TestHarness() {+ const {contentRef} = useXDSChatNewMessages({isLocked: true, onResize});+ const [mounted, setMounted] = useState(false);++ return (+ <>+ <button+ type="button"+ data-testid="mount"+ onClick={() => setMounted(true)}>+ Mount+ </button>+ {mounted && (+ <div ref={contentRef} data-testid="content">+ <div className="xds-chat-message">msg</div>+ </div>+ )}+ </>+ );+ }++ const {getByTestId} = render(<TestHarness />);++ // Before mount — no element, no observer+ expect(onResize).not.toHaveBeenCalled();++ // Mount the content element+ act(() => {+ getByTestId('mount').click();+ });++ // Callback ref fires → observer attaches → initial callback → onResize+ expect(onResize).toHaveBeenCalled();+ });++ it('detaches observer when element unmounts', () => {+ const onResize = vi.fn();++ function TestHarness() {+ const {contentRef} = useXDSChatNewMessages({isLocked: true, onResize});+ const [mounted, setMounted] = useState(true);++ return (+ <>+ <button+ type="button"+ data-testid="unmount"+ onClick={() => setMounted(false)}>+ Unmount+ </button>+ {mounted && (+ <div ref={contentRef} data-testid="content">+ <div className="xds-chat-message">msg</div>+ </div>+ )}+ </>+ );+ }++ const {getByTestId} = render(<TestHarness />);+ expect(onResize).toHaveBeenCalled();++ const observationsBefore = activeObservations.length;++ act(() => {+ getByTestId('unmount').click();+ });++ // Observer should have been detached+ expect(activeObservations.length).toBeLessThan(observationsBefore);+ });++ it('works end-to-end with XDSChatLayout conditional XDSChatMessageList', () => {+ function TestApp() {+ const [messages, setMessages] = useState<string[]>([]);++ return (+ <>+ <button+ type="button"+ data-testid="add-message"+ onClick={() =>+ setMessages(prev => [...prev, `msg-${prev.length}`])+ }>+ Add+ </button>+ <XDSChatLayout+ composer={<div>composer</div>}+ emptyState={<div>Empty state</div>}>+ {messages.length > 0 && (+ <XDSChatMessageList>+ {messages.map(msg => (+ <XDSChatMessage key={msg} sender="assistant">+ <XDSChatMessageBubble>{msg}</XDSChatMessageBubble>+ </XDSChatMessage>+ ))}+ </XDSChatMessageList>+ )}+ </XDSChatLayout>+ </>+ );+ }++ const {getByTestId, getByText} = render(<TestApp />);++ // Empty state showing — no content observer yet+ expect(getByText('Empty state')).toBeInTheDocument();++ // Add first message — XDSChatMessageList mounts+ act(() => {+ getByTestId('add-message').click();+ });++ expect(getByText('msg-0')).toBeInTheDocument();++ // The inner content div should now be observed+ const contentObservation = activeObservations.find(o => {+ const el = o.element;+ if (!el.querySelector?.('.xds-chat-message')) {+ return false;+ }+ if (el.className?.includes('xds-chat-layout')) {+ return false;+ }+ return true;+ });++ expect(contentObservation).toBeDefined();+ });+});diff --git a/packages/core/src/Chat/useXDSChatNewMessages.ts b/packages/core/src/Chat/useXDSChatNewMessages.tsindex 36405a1c89..b12ba8a65a 100644--- a/packages/core/src/Chat/useXDSChatNewMessages.ts+++ b/packages/core/src/Chat/useXDSChatNewMessages.ts@@ -15,6 +15,10 @@* Also calls onResize on every content height change so the scroll* hook can follow growing content (streaming).*+ * Returns a callback ref — pass it as the contentRef in the layout+ * context. When the element mounts (even late), the observer attaches+ * automatically without needing state or version counters.+ ** SYNC: When modified, update:* - /packages/core/src/Chat/index.ts (exports)*/@@ -27,12 +31,6 @@ import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';// =============================================================================export interface UseXDSChatNewMessagesOptions {- /**- * Ref to the content element to observe (message list inner div).- * Can be a callback ref or a regular ref.- */- contentRef: React.RefObject<HTMLElement | null>;-/*** Whether the scroll is currently locked (following content).* When locked, new messages don't flag — the user is already at the bottom.@@ -52,6 +50,12 @@ export interface UseXDSChatNewMessagesReturn {/** Dismiss the new messages flag. */dismiss: () => void;++ /**+ * Callback ref to attach to the content element.+ * Handles late mount — observer attaches whenever the element appears.+ */+ contentRef: (el: HTMLElement | null) => void;}// =============================================================================@@ -59,7 +63,6 @@ export interface UseXDSChatNewMessagesReturn {// =============================================================================export function useXDSChatNewMessages({- contentRef,isLocked,onResize,}: UseXDSChatNewMessagesOptions): UseXDSChatNewMessagesReturn {@@ -71,36 +74,61 @@ export function useXDSChatNewMessages({const onResizeRef = useRef(onResize);onResizeRef.current = onResize;- // Observe content for height changes- useEffect(() => {- const el = contentRef.current;- if (!el) {- return;- }+ // Track the current content element. When the callback ref fires,+ // we tear down the old observer and set up a new one.+ const elementRef = useRef<HTMLElement | null>(null);+ const cleanupRef = useRef<(() => void) | null>(null);+ const attach = useCallback((el: HTMLElement) => {observeResize(el, () => {- // Notify scroll hook of any height changeonResizeRef.current?.();- // Check if a new message was appendedconst messages = el.getElementsByClassName('xds-chat-message');const last = messages.length > 0 ? messages[messages.length - 1] : null;if (last && last !== lastMessageRef.current) {lastMessageRef.current = last;- // Only flag if unlocked — user is scrolled upif (!isLockedRef.current) {setHasNewMessages(true);}}});- return () => unobserveResize(el);- }, [contentRef]);+ cleanupRef.current = () => unobserveResize(el);+ }, []);++ const detach = useCallback(() => {+ cleanupRef.current?.();+ cleanupRef.current = null;+ }, []);++ // Callback ref — handles mount, unmount, and element swap+ const contentRef = useCallback(+ (el: HTMLElement | null) => {+ if (el === elementRef.current) {+ return;+ }++ // Detach from previous element+ detach();+ elementRef.current = el;++ // Attach to new element+ if (el) {+ attach(el);+ }+ },+ [attach, detach],+ );++ // Cleanup on unmount+ useEffect(() => {+ return () => detach();+ }, [detach]);const dismiss = useCallback(() => {setHasNewMessages(false);}, []);- return {hasNewMessages, dismiss};+ return {hasNewMessages, dismiss, contentRef};}