diff --git a/src/frontend/src/features/rooms/livekit/prefabs/Chat.tsx b/src/frontend/src/features/rooms/livekit/prefabs/Chat.tsx index a1f92256..71f2ad20 100644 --- a/src/frontend/src/features/rooms/livekit/prefabs/Chat.tsx +++ b/src/frontend/src/features/rooms/livekit/prefabs/Chat.tsx @@ -4,6 +4,7 @@ import { formatChatMessageLinks, useChat, useParticipants, + useRoomContext, } from '@livekit/components-react' import { useTranslation } from 'react-i18next' import { useSnapshot } from 'valtio' @@ -12,6 +13,7 @@ import { Div, Text } from '@/primitives' import { ChatInput } from '../components/chat/Input' import { ChatEntry } from '../components/chat/Entry' import { useSidePanel } from '../hooks/useSidePanel' +import { LocalParticipant, RemoteParticipant, RoomEvent } from 'livekit-client' export interface ChatProps extends React.HTMLAttributes, @@ -27,6 +29,7 @@ export function Chat({ ...props }: ChatProps) { const inputRef = React.useRef(null) const ulRef = React.useRef(null) + const room = useRoomContext() const { send, chatMessages, isSending } = useChat() const { isChatOpen } = useSidePanel() @@ -36,6 +39,7 @@ export function Chat({ ...props }: ChatProps) { const participants = useParticipants() const lastReadMsgAt = React.useRef(0) + const previousMessageCount = React.useRef(0) async function handleSubmit(text: string) { if (!send || !text) return @@ -43,6 +47,19 @@ export function Chat({ ...props }: ChatProps) { inputRef?.current?.focus() } + // TEMPORARY: This is a brittle workaround that relies on message count tracking + // due to recent LiveKit useChat changes breaking the previous implementation + // (see https://github.com/livekit/components-js/issues/1158) + // Remove this once we refactor chat to use the new text stream approach + React.useEffect(() => { + if (!chatMessages || chatMessages.length <= previousMessageCount.current) + return + const msg = chatMessages.slice(-1)[0] + const from = msg.from as RemoteParticipant | LocalParticipant | undefined + room.emit(RoomEvent.ChatMessage, msg, from) + previousMessageCount.current = chatMessages.length + }, [chatMessages, room]) + React.useEffect(() => { if (chatMessages.length > 0 && ulRef.current) { ulRef.current?.scrollTo({ top: ulRef.current.scrollHeight })