- 流式回答过程中点「新对话」:URL 同路径导致 react-router navigate 静默 no-op,
下游 hook 收不到事件;改为显式 navigate(..., {replace:true, state:{resetAt}})
保证每次点击刷新 location.key,并让 useThreadChat 监听 location.key 触发重置
- useThreadStream 在 threadId 变化时 stop() 掉上一条 SSE,避免旧流继续派发事件
- 引入 KeyedChatPage 用 location.key 作 ChatRuntime key,真正的导航触发整树 remount,
解决 useStream 内部 stream.values 残留导致欢迎页底下还能看到旧消息的过渡帧问题
- 「参考文献」开关默认关闭(local.ts),开启态在文字前额外多一个 ✓ 对勾
51 lines
1.9 KiB
TypeScript
51 lines
1.9 KiB
TypeScript
"use client";
|
|
|
|
import { useParams, usePathname, useSearchParams } from "next/navigation";
|
|
import { useEffect, useState } from "react";
|
|
import { useLocation } from "react-router-dom";
|
|
|
|
import { uuid } from "@/core/utils/uuid";
|
|
|
|
export function useThreadChat() {
|
|
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
|
|
const pathname = usePathname();
|
|
// ``location.key`` is regenerated on every react-router navigation, even when
|
|
// the resolved pathname is identical. We depend on it so that clicking
|
|
// "新对话" while already at /chats/new still triggers a fresh thread reset
|
|
// (otherwise navigate-to-same-path is silently a no-op and the in-flight
|
|
// conversation would persist on screen).
|
|
const locationKey = useLocation().key;
|
|
|
|
const searchParams = useSearchParams();
|
|
const [threadId, setThreadId] = useState(() => {
|
|
return threadIdFromPath === "new" ? uuid() : threadIdFromPath;
|
|
});
|
|
|
|
const [isNewThread, setIsNewThread] = useState(
|
|
() => threadIdFromPath === "new",
|
|
);
|
|
|
|
useEffect(() => {
|
|
const onNewChatPath =
|
|
pathname.endsWith("/new") ||
|
|
(pathname === "/" && threadIdFromPath === "new");
|
|
if (onNewChatPath) {
|
|
setIsNewThread(true);
|
|
setThreadId(uuid());
|
|
return;
|
|
}
|
|
// Guard: after history.replaceState updates the URL from /chats/new to
|
|
// /chats/{UUID}, Next.js useParams may still return the stale "new" value
|
|
// because replaceState does not trigger router updates. Avoid propagating
|
|
// this invalid thread ID to downstream hooks (e.g. useStream), which would
|
|
// cause a 422 from LangGraph Server.
|
|
if (threadIdFromPath === "new") {
|
|
return;
|
|
}
|
|
setIsNewThread(false);
|
|
setThreadId(threadIdFromPath);
|
|
}, [pathname, threadIdFromPath, locationKey]);
|
|
const isMock = searchParams.get("mock") === "true";
|
|
return { threadId, setThreadId, isNewThread, setIsNewThread, isMock };
|
|
}
|