Skip to content

An AI-powered search engine with a generative UI

fix(chat): ignore Related-question clicks while a response is streaming (#853)

Eliauk82ce67dd1e65
diff --git a/components/chat.tsx b/components/chat.tsx
index 22d5e7c7..5660013e 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -1,6 +1,6 @@
'use client'
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useChat } from '@ai-sdk/react'
@@ -86,6 +86,14 @@ export function Chat({
message: ''
})
+ // Locally-maintained streaming flag exposed through ChatContext so
+ // programmatic dispatch sites (e.g. Related-question buttons in
+ // spec-block) can throttle clicks. Held in a ref so closures
+ // captured by @json-render/react's ActionProvider (which freezes
+ // its `handlers` prop via useState(initialHandlers)) can still see
+ // the freshest value through `.current`. See lib/contexts/chat-context.tsx.
+ const isStreamingRef = useRef(false)
+
const {
messages,
status,
@@ -130,9 +138,11 @@ export function Chat({
}),
messages: savedMessages,
onFinish: () => {
+ isStreamingRef.current = false
window.dispatchEvent(new CustomEvent('chat-history-updated'))
},
onError: error => {
+ isStreamingRef.current = false
// Handle rate limiting errors from Vercel WAF
// Check for status codes in error message or specific rate limit indicators
const errorMessage = error.message?.toLowerCase() || ''
@@ -216,6 +226,17 @@ export function Chat({
generateId
})
+ // Wrap sendMessage so every dispatch flips isStreamingRef on; onFinish
+ // and onError flip it off. Use this in place of the raw sendMessage at
+ // every call site so the throttle is uniform.
+ const safeSendMessage = useCallback<typeof sendMessage>(
+ (...args) => {
+ isStreamingRef.current = true
+ return sendMessage(...args)
+ },
+ [sendMessage]
+ )
+
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value)
}
@@ -439,7 +460,7 @@ export function Chat({
})
})
- sendMessage({ role: 'user', parts })
+ safeSendMessage({ role: 'user', parts })
setInput('')
setUploadedFiles([])
@@ -474,7 +495,10 @@ export function Chat({
: { isDragging, handleDragOver, handleDragLeave, handleDrop }
return (
- <ChatProvider sendMessage={sendMessage}>
+ <ChatProvider
+ sendMessage={safeSendMessage}
+ isStreamingRef={isStreamingRef}
+ >
<div
className={cn(
'relative flex h-full min-w-0 flex-1 flex-col',
@@ -542,7 +566,7 @@ export function Chat({
stop={stop}
query={query}
append={(message: any) => {
- sendMessage(message)
+ safeSendMessage(message)
}}
showScrollToBottomButton={!isAtBottom}
uploadedFiles={uploadedFiles}
@@ -568,7 +592,7 @@ export function Chat({
.filter(m => m.role === 'user')
.pop()
if (lastUserMessage) {
- sendMessage(lastUserMessage)
+ safeSendMessage(lastUserMessage)
}
}
}
diff --git a/components/spec-block.tsx b/components/spec-block.tsx
index c199a203..aba15ad2 100644
--- a/components/spec-block.tsx
+++ b/components/spec-block.tsx
@@ -3,6 +3,7 @@
import { useMemo } from 'react'
import { ActionProvider, JSONUIProvider, Renderer } from '@json-render/react'
+import { toast } from 'sonner'
import { useChatContext } from '@/lib/contexts/chat-context'
import { registry } from '@/lib/render/registry'
@@ -19,12 +20,22 @@ export function SpecBlock({ result }: SpecBlockProps) {
() => ({
submitQuery: (params: Record<string, unknown>) => {
const query = (params as { query?: string }).query
- if (typeof query === 'string' && query.trim()) {
- chatContext.sendMessage({
- role: 'user',
- parts: [{ type: 'text', text: query }]
- })
+ if (typeof query !== 'string' || !query.trim()) return
+
+ // Reject clicks while a response is in flight. Firing a second
+ // sendMessage mid-stream corrupts useChat's internal state and
+ // leaves the input box stuck disabled. Read via the ref so the
+ // frozen closure (ActionProvider stores handlers as
+ // useState(initialHandlers)) still sees the latest value.
+ if (chatContext.isStreamingRef.current) {
+ toast.info('Please wait for the current response to finish.')
+ return
}
+
+ chatContext.sendMessage({
+ role: 'user',
+ parts: [{ type: 'text', text: query }]
+ })
}
}),
[chatContext]
diff --git a/lib/contexts/chat-context.tsx b/lib/contexts/chat-context.tsx
index 718dafcc..dfc69cf6 100644
--- a/lib/contexts/chat-context.tsx
+++ b/lib/contexts/chat-context.tsx
@@ -1,5 +1,6 @@
'use client'
+import type { MutableRefObject } from 'react'
import { createContext, useContext } from 'react'
type ChatContextValue = {
@@ -7,16 +8,25 @@ type ChatContextValue = {
role: 'user'
parts: Array<{ type: 'text'; text: string }>
}) => void
+ // Ref (not state) so reads via `.current` always see the freshest
+ // value, even when the consumer is downstream of
+ // @json-render/react's ActionProvider — which captures its handlers
+ // prop into useState(initialHandlers) and never refreshes them,
+ // making any React-state value read through closure go stale on the
+ // very next render. Maintained by chat.tsx: set to true inside
+ // safeSendMessage, cleared inside useChat's onFinish / onError.
+ isStreamingRef: MutableRefObject<boolean>
}
const ChatContext = createContext<ChatContextValue | null>(null)
export function ChatProvider({
sendMessage,
+ isStreamingRef,
children
}: ChatContextValue & { children: React.ReactNode }) {
return (
- <ChatContext.Provider value={{ sendMessage }}>
+ <ChatContext.Provider value={{ sendMessage, isStreamingRef }}>
{children}
</ChatContext.Provider>
)