diff --git a/app/components/chat.tsx b/app/components/chat.tsx index 5669cc9a3147..18353e28ac3b 100644 --- a/app/components/chat.tsx +++ b/app/components/chat.tsx @@ -960,9 +960,29 @@ function _Chat() { (scrollRef.current.scrollTop + scrollRef.current.clientHeight), ) <= 1 : false; + const isAttachWithTop = useCallback(() => { + // if user is typing, should scroll + if (!scrollRef.current) return false; + // get lastMessageId + const lastMessageId = session.messages[session.messages.length - 1]?.id; + if (!lastMessageId) return false; + const lastMessage = document.getElementById(lastMessageId); + if (!lastMessage) return false; + + const topDistance = + lastMessage.getBoundingClientRect().top - + scrollRef.current.getBoundingClientRect().top; + // leave some space for user question + return topDistance < 100; + }, [session.messages, scrollRef]); + + const isTyping = userInput !== ""; + + // if user is typing, should auto scroll to bottom + // if user is not typing, should auto scroll to bottom only if already at bottom const { setAutoScroll, scrollDomToBottom } = useScrollToBottom( scrollRef, - isScrolledToBottom, + (isScrolledToBottom || isAttachWithTop()) && !isTyping, ); const [hitBottom, setHitBottom] = useState(true); const isMobileScreen = useMobileScreen(); @@ -1717,6 +1737,7 @@ function _Chat() { ? styles["chat-message-user"] : styles["chat-message"] } + id={message.id} >