Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions frontend/src/routes/_auth.chat.$chatId.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -327,17 +327,44 @@ function ChatComponent() {
const isLoading = phase === "streaming";
const isPersisting = phase === "persisting";

// Auto-scroll when new messages appear (user message or start of streaming)
// Auto-scroll when user messages are added or streaming starts
const prevMessageCountRef = useRef(localChat.messages.length);
const prevStreamingRef = useRef(false);
const streamStartedRef = useRef(false);

useEffect(() => {
const messageCount = localChat.messages.length;
const hasNewMessage = messageCount > prevMessageCountRef.current;
const justStartedStreaming = isLoading && !prevStreamingRef.current;
const justStoppedStreaming = !isLoading && prevStreamingRef.current;

if (hasNewMessage || justStartedStreaming) {
// Always scroll for new user messages or when streaming starts
// Track when streaming actually starts
if (justStartedStreaming) {
streamStartedRef.current = true;
}

// Only auto-scroll for user messages or when streaming starts
// Don't auto-scroll when assistant messages are added (streaming completion)
let shouldAutoScroll = false;

if (justStartedStreaming) {
// Always scroll when streaming starts
shouldAutoScroll = true;
} else if (hasNewMessage && !justStoppedStreaming) {
// Only scroll for new user messages, not assistant messages
// Also don't scroll if we just stopped streaming (assistant message completion)
const latestMessage = localChat.messages[localChat.messages.length - 1];
if (latestMessage?.role === "user") {
shouldAutoScroll = true;
}
}

// Reset stream tracking when streaming stops
if (justStoppedStreaming) {
streamStartedRef.current = false;
}

if (shouldAutoScroll) {
const container = chatContainerRef.current;
if (container) {
requestAnimationFrame(() => {
Expand All @@ -351,7 +378,7 @@ function ChatComponent() {

prevMessageCountRef.current = messageCount;
prevStreamingRef.current = isLoading;
}, [localChat.messages.length, isLoading]);
}, [localChat.messages.length, isLoading, localChat.messages]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Adding localChat.messages as a dependency may cause unnecessary re-renders since the array reference changes on every message update, even when length hasn't changed. Consider removing this dependency since localChat.messages.length already triggers the effect when needed.

Suggested change
}, [localChat.messages.length, isLoading, localChat.messages]);
}, [localChat.messages.length, isLoading]);


const sendMessage = useCallback(
async (
Expand Down