An open source design system that's fully customizable and agent ready
TypeScript
fix(Chat): latest-value refs are written at commit (#10162)
Christopher Chedeaudf0e60e70d17
diff --git a/.changeset/chat-new-messages-committed-refs.md b/.changeset/chat-new-messages-committed-refs.mdnew file mode 100644index 0000000000..7bf3ed102f--- /dev/null+++ b/.changeset/chat-new-messages-committed-refs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `useChatNewMessages` (which `ChatLayout` uses), `useSpeechRecognition` and `useChatDictation` read their callbacks and other latest values as last committed. A render that React discards, as a suspended transition does, no longer has its callbacks called on the next resize or recognition event. Its audio context is no longer used either. After such a render, `useChatNewMessages` also no longer flags new messages while the list follows the bottom.++@vjeuxdiff --git a/packages/core/src/Chat/useChatDictation.test.tsx b/packages/core/src/Chat/useChatDictation.test.tsxindex cc9ea9d0bc..7b42d0b744 100644--- a/packages/core/src/Chat/useChatDictation.test.tsx+++ b/packages/core/src/Chat/useChatDictation.test.tsx@@ -1,8 +1,8 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import type {ReactNode} from 'react';+import {Suspense, startTransition, use, type ReactNode} from 'react';import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';-import {renderHook, act} from '@testing-library/react';+import {act, render, renderHook} from '@testing-library/react';import {InternationalizationProvider} from '../i18n';import {useSpeechRecognition} from './useSpeechRecognition';import {useChatDictation} from './useChatDictation';@@ -367,3 +367,165 @@ describe('useChatDictation', () => {expect(lastInstance?.abort).toHaveBeenCalled();});});++// =============================================================================+// Values from a render React discards+// =============================================================================++describe('callbacks and audio context as last committed', () => {+ const pending = new Promise<never>(() => {});+ function Pending(): null {+ use(pending);+ return null;+ }+ function Screen({+ children,+ isPending,+ }: {+ children: ReactNode;+ isPending: boolean;+ }) {+ return (+ <Suspense fallback={null}>+ {children}+ {isPending ? <Pending /> : null}+ </Suspense>+ );+ }+ // An audio graph call throws, so each hook stops at the first call it+ // makes, and the test can tell which context it reached.+ const noAudioGraph = () => {+ throw new Error('no audio graph in tests');+ };++ it('useSpeechRecognition keeps the committed callbacks and audio context when React discards a render, as a suspended transition does', async () => {+ const committedStart = vi.fn();+ const discardedStart = vi.fn();+ // The volume analyser asks for the microphone, then for its context.+ // The test waits for that second step, whichever context it reaches.+ let reached: (context: string) => void = () => {};+ const reachedContext = new Promise<string>(resolve => {+ reached = resolve;+ });+ const contextNamed = (name: string) => ({+ createMediaStreamSource: vi.fn(() => {+ reached(name);+ noAudioGraph();+ }),+ });+ const committedContext = contextNamed('committed');+ const discardedContext = contextNamed('discarded');+ Object.defineProperty(navigator, 'mediaDevices', {+ configurable: true,+ value: {getUserMedia: async () => ({}) as MediaStream},+ });+ function Recognizer({+ onStart,+ audioContext,+ }: {+ onStart: () => void;+ audioContext: object;+ }) {+ const speech = useSpeechRecognition({+ onStart,+ audioContext: audioContext as AudioContext,+ });+ return (+ <button type="button" onClick={speech.start}>+ Start+ </button>+ );+ }+ try {+ const {getByRole, rerender} = render(+ <Screen isPending={false}>+ <Recognizer+ onStart={committedStart}+ audioContext={committedContext}+ />+ </Screen>,+ );+ // The transition renders new callbacks and a new context, then+ // suspends for good, so React keeps the committed tree and never+ // commits that render.+ await act(async () => {+ startTransition(() => {+ rerender(+ <Screen isPending>+ <Recognizer+ onStart={discardedStart}+ audioContext={discardedContext}+ />+ </Screen>,+ );+ });+ });+ act(() => {+ getByRole('button', {name: 'Start'}).click();+ });+ expect(await reachedContext).toBe('committed');+ expect(discardedStart).not.toHaveBeenCalled();+ expect(committedStart).toHaveBeenCalledTimes(1);+ } finally {+ delete (navigator as unknown as {mediaDevices?: unknown}).mediaDevices;+ }+ });++ it('useChatDictation keeps the committed callbacks and audio context when React discards a render, as a suspended transition does', async () => {+ const committedStart = vi.fn();+ const discardedStart = vi.fn();+ const committedContext = {+ currentTime: 0,+ createOscillator: vi.fn(noAudioGraph),+ };+ const discardedContext = {+ currentTime: 0,+ createOscillator: vi.fn(noAudioGraph),+ };+ function Dictation({+ onStart,+ audioContext,+ }: {+ onStart: () => void;+ audioContext: object;+ }) {+ const dictation = useChatDictation({+ onStart,+ audioContext: audioContext as AudioContext,+ hasSounds: true,+ });+ return (+ <button type="button" onClick={dictation.start}>+ Start+ </button>+ );+ }+ const {getByRole, rerender} = render(+ <Screen isPending={false}>+ <Dictation onStart={committedStart} audioContext={committedContext} />+ </Screen>,+ );+ // The transition renders new callbacks and a new context, then suspends+ // for good, so React keeps the committed tree and never commits that+ // render.+ await act(async () => {+ startTransition(() => {+ rerender(+ <Screen isPending>+ <Dictation+ onStart={discardedStart}+ audioContext={discardedContext}+ />+ </Screen>,+ );+ });+ });+ act(() => {+ getByRole('button', {name: 'Start'}).click();+ });+ expect(discardedStart).not.toHaveBeenCalled();+ expect(committedStart).toHaveBeenCalledTimes(1);+ expect(discardedContext.createOscillator).not.toHaveBeenCalled();+ expect(committedContext.createOscillator).toHaveBeenCalled();+ });+});diff --git a/packages/core/src/Chat/useChatDictation.ts b/packages/core/src/Chat/useChatDictation.tsindex 42cc0a10dd..de2b0b9998 100644--- a/packages/core/src/Chat/useChatDictation.ts+++ b/packages/core/src/Chat/useChatDictation.ts@@ -16,6 +16,7 @@import {useState, useCallback, useEffect, useRef} from 'react';import type {ChatComposerInputHandle} from './ChatComposerInput';import {useSpeechRecognition} from './useSpeechRecognition';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';// =============================================================================// Types@@ -292,7 +293,6 @@ export function useChatDictation(const volumeHistoryRef = useRef<number[]>([]);const getAudioContextRef = useRef(getAudioContext);- getAudioContextRef.current = getAudioContext;const analyserRef = useRef<VolumeAnalyser | null>(null);const rafRef = useRef<number>(0);const interimSpanRef = useRef<HTMLSpanElement | null>(null);@@ -303,12 +303,18 @@ export function useChatDictation(onStartProp,onEndProp,});- callbacksRef.current = {- onTranscriptProp,- onResultProp,- onStartProp,- onEndProp,- };+ // Recognition events read the latest callbacks and audio context. Write+ // them at commit: a render React discards, as a suspended transition does,+ // must not leave its values behind.+ useIsomorphicLayoutEffect(() => {+ getAudioContextRef.current = getAudioContext;+ callbacksRef.current = {+ onTranscriptProp,+ onResultProp,+ onStartProp,+ onEndProp,+ };+ });const startVolumePolling = useCallback(() => {const poll = () => {diff --git a/packages/core/src/Chat/useChatNewMessages.test.tsx b/packages/core/src/Chat/useChatNewMessages.test.tsxindex f68f5dec26..9c4a95793d 100644--- a/packages/core/src/Chat/useChatNewMessages.test.tsx+++ b/packages/core/src/Chat/useChatNewMessages.test.tsx@@ -2,7 +2,7 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {render, act} from '@testing-library/react';-import {useState} from 'react';+import {Suspense, startTransition, use, useState} from 'react';import {ChatLayout} from './ChatLayout';import {ChatMessageList} from './ChatMessageList';import {ChatMessage} from './ChatMessage';@@ -207,3 +207,118 @@ describe('useChatNewMessages — callback ref (issue #2282)', () => {expect(contentObservation).toBeDefined();});});++describe('useChatNewMessages — committed values', () => {+ it('keeps the committed lock and onResize when React discards a render, as a suspended transition does', async () => {+ const committed = vi.fn();+ const discarded = vi.fn();+ const pending = new Promise<never>(() => {});+ function Pending(): null {+ use(pending);+ return null;+ }+ function Content({+ isLocked,+ onResize,+ }: {+ isLocked: boolean;+ onResize: () => void;+ }) {+ const {contentRef, hasNewMessages} = useChatNewMessages({+ isLocked,+ onResize,+ });+ return (+ <div+ ref={contentRef}+ data-testid="content"+ data-new-messages={String(hasNewMessages)}>+ <div className="astryx-chat-message">first</div>+ </div>+ );+ }+ function Screen({+ isLocked,+ onResize,+ isPending,+ }: {+ isLocked: boolean;+ onResize: () => void;+ isPending: boolean;+ }) {+ return (+ <Suspense fallback={null}>+ <Content isLocked={isLocked} onResize={onResize} />+ {isPending ? <Pending /> : null}+ </Suspense>+ );+ }+ const {getByTestId, rerender} = render(+ <Screen isLocked onResize={committed} isPending={false} />,+ );+ // The transition renders an unlocked list and a new onResize, then+ // suspends for good, so React keeps the committed tree and never commits+ // that render.+ await act(async () => {+ startTransition(() => {+ rerender(<Screen isLocked={false} onResize={discarded} isPending />);+ });+ });+ committed.mockClear();+ // A message arrives and the content grows.+ const content = getByTestId('content');+ act(() => {+ const message = document.createElement('div');+ message.className = 'astryx-chat-message';+ content.append(message);+ const entry: Partial<ResizeObserverEntry> = {target: content};+ for (const {element, callback} of activeObservations) {+ if (element === content) {+ callback([entry as ResizeObserverEntry], {} as ResizeObserver);+ }+ }+ });+ expect(discarded).not.toHaveBeenCalled();+ expect(committed).toHaveBeenCalled();+ expect(content.dataset.newMessages).toBe('false');+ });++ it('reads the lock and onResize of the commit that attaches a new content element', () => {+ const first = vi.fn();+ const second = vi.fn();+ function Content({+ isLocked,+ onResize,+ element,+ }: {+ isLocked: boolean;+ onResize: () => void;+ element: string;+ }) {+ const {contentRef, hasNewMessages} = useChatNewMessages({+ isLocked,+ onResize,+ });+ return (+ <div+ key={element}+ ref={contentRef}+ data-testid="content"+ data-new-messages={String(hasNewMessages)}>+ <div className="astryx-chat-message">{element}</div>+ </div>+ );+ }+ const {getByTestId, rerender} = render(+ <Content isLocked onResize={first} element="a" />,+ );+ rerender(<Content isLocked={false} onResize={first} element="a" />);+ first.mockClear();+ // One commit swaps the content element and locks the list. The observer+ // calls back as the new element attaches.+ rerender(<Content isLocked onResize={second} element="b" />);+ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalled();+ expect(getByTestId('content').dataset.newMessages).toBe('false');+ });+});diff --git a/packages/core/src/Chat/useChatNewMessages.ts b/packages/core/src/Chat/useChatNewMessages.tsindex b175989f5f..79110788aa 100644--- a/packages/core/src/Chat/useChatNewMessages.ts+++ b/packages/core/src/Chat/useChatNewMessages.ts@@ -23,7 +23,13 @@* - /packages/core/src/Chat/index.ts (exports)*/-import {useCallback, useEffect, useRef, useState} from 'react';+import {+ useCallback,+ useEffect,+ useInsertionEffect,+ useRef,+ useState,+} from 'react';import {observeResize} from '../utils/sharedResizeObserver';// =============================================================================@@ -69,10 +75,12 @@ export function useChatNewMessages({const [hasNewMessages, setHasNewMessages] = useState(false);const lastMessageRef = useRef<Element | null>(null);const isLockedRef = useRef(isLocked);- isLockedRef.current = isLocked;-const onResizeRef = useRef(onResize);- onResizeRef.current = onResize;+ // The ref callback and the observer's first call run before layout Effects.+ useInsertionEffect(() => {+ isLockedRef.current = isLocked;+ onResizeRef.current = onResize;+ });// Track the current content element. When the callback ref fires,// we tear down the old observer and set up a new one.diff --git a/packages/core/src/Chat/useSpeechRecognition.ts b/packages/core/src/Chat/useSpeechRecognition.tsindex 4b95101973..f9dbba0573 100644--- a/packages/core/src/Chat/useSpeechRecognition.ts+++ b/packages/core/src/Chat/useSpeechRecognition.ts@@ -15,6 +15,7 @@import {useState, useCallback, useEffect, useMemo, useRef} from 'react';import {useLocale} from '../i18n';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {registerEnglishFallback,useComponentTranslator,@@ -296,7 +297,6 @@ export function useSpeechRecognition(const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);const getAudioContextRef = useRef(getAudioContext);- getAudioContextRef.current = getAudioContext;const analyserRef = useRef<VolumeAnalyser | null>(null);const rafRef = useRef<number>(0);@@ -308,14 +308,20 @@ export function useSpeechRecognition(onEnd,transformTranscript,});- callbacksRef.current = {- onTranscript,- onResult,- onError,- onStart,- onEnd,- transformTranscript,- };+ // Recognition events read the latest callbacks and audio context. Write+ // them at commit: a render React discards, as a suspended transition does,+ // must not leave its values behind.+ useIsomorphicLayoutEffect(() => {+ getAudioContextRef.current = getAudioContext;+ callbacksRef.current = {+ onTranscript,+ onResult,+ onError,+ onStart,+ onEnd,+ transformTranscript,+ };+ });// Releases speech recognition, the audio analyser and the animation frame on// unmount.