From b36edf51f1c25607f5ea920228fe1c6653215b7a Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 19 Dec 2025 02:01:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=A1=B5=E9=9D=A2=E5=88=87?= =?UTF-8?q?=E6=8D=A2=E5=90=8E=E5=9B=BE=E7=89=87=E7=94=9F=E6=88=90=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E4=B8=8D=E6=9B=B4=E6=96=B0=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/chat.tsx | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/components/chat.tsx b/components/chat.tsx index ff0c718..7701944 100644 --- a/components/chat.tsx +++ b/components/chat.tsx @@ -65,6 +65,33 @@ export function Chat({ // 🆕 持久化生成任务状态(解决用户离开再返回时加载状态丢失) const { pendingGeneration, startGeneration, completeGeneration } = usePendingGeneration(id); + + // 🆕 标记是否已经尝试刷新过(避免无限刷新) + const hasTriedRefreshRef = useRef(false); + + // 🆕 当检测到恢复的 pendingGeneration 时,刷新页面获取最新消息 + useEffect(() => { + if (pendingGeneration && !hasTriedRefreshRef.current) { + // 检查最后一条消息是否已经是 AI 回复 + const lastMessage = initialMessages.length > 0 ? initialMessages[initialMessages.length - 1] : null; + + if (lastMessage?.role === "assistant") { + // 最后一条已经是 AI 回复,说明生成已完成,清除 pending 状态 + console.log("[Chat] 🎉 检测到生成已完成(最后消息是 AI 回复),清除 pending 状态"); + completeGeneration(); + } else if (lastMessage?.role === "user") { + // 最后一条是用户消息,可能还在生成中,或者已经完成但页面数据过期 + // 标记已尝试刷新,然后刷新页面获取最新数据 + hasTriedRefreshRef.current = true; + console.log("[Chat] 🔄 检测到恢复的 pending 状态,刷新页面获取最新消息..."); + + // 延迟一小段时间再刷新,避免立即刷新 + setTimeout(() => { + router.refresh(); + }, 500); + } + } + }, [pendingGeneration, initialMessages, completeGeneration, router]); const { mutate } = useSWRConfig();