Skip to content
Merged
Changes from 1 commit
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
37 changes: 35 additions & 2 deletions src/components/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useChat } from 'ai/react'
import { MessageSquarePlus } from 'lucide-react'
import { useModel } from '../contexts/ModelContext'
Expand Down Expand Up @@ -61,6 +61,7 @@ const TIMEOUT_ERROR_MESSAGE =
export function Chat() {
const hasMounted = useHasMounted()
const messagesEndRef = useRef<HTMLDivElement>(null)
const seenMessageIds = useRef(new Set<string>())
const [hasStartedChat, setHasStartedChat] = useState(false)
const [focusTimestamp, setFocusTimestamp] = useState(Date.now())
const [servers, setServers] = useState<Servers>({})
Expand Down Expand Up @@ -127,9 +128,40 @@ export function Chat() {
onResponse: handleResponse,
})

useEffect(() => {
if (!streaming && streamBuffer.length > 0) {
// Extract only assistant messages from streamBuffer (user messages are already in messages via append)
const assistantEvents = streamBuffer.filter(
(event): event is Extract<StreamEvent, { type: 'assistant' }> =>
event.type === 'assistant',
)

if (assistantEvents.length > 0) {
setMessages((prevMessages) => {
// Convert assistant stream events to Message objects, filtering duplicates using ref
const newMessages = assistantEvents
.filter((event) => !seenMessageIds.current.has(event.id))
.map((event) => ({
id: event.id,
role: 'assistant' as const,
content: event.content,
}))

// Track newly added message IDs
newMessages.forEach((msg) => seenMessageIds.current.add(msg.id))

return [...prevMessages, ...newMessages]
})
}

// Clear the buffer after syncing to prevent old messages from accumulating
clearBuffer()
}
}, [streaming, streamBuffer, setMessages, clearBuffer])

const renderEvents = useMemo<Array<StreamEvent | Message>>(() => {
if (streaming || streamBuffer.length > 0) {
return [...streamBuffer]
return [...messages, ...streamBuffer]
}
// Show initial message only when there are no real messages and no streaming
if (messages.length === 0 && !hasStartedChat) {
Expand Down Expand Up @@ -164,6 +196,7 @@ export function Chat() {
setHasStartedChat(false)
clearBuffer()
setMessages([])
seenMessageIds.current.clear()
setFocusTimestamp(Date.now())
setUseCodeInterpreter(false)
setUseWebSearch(false)
Expand Down
Loading