修复「新对话」流式中无法重置 + 参考文献开关默认关闭并加对勾
- 流式回答过程中点「新对话」: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),开启态在文字前额外多一个 ✓ 对勾
This commit is contained in:
1 parent
97f24f17eb
commit
7adb93fb8e
6 files changed
+120
-62
No files matched your search
@@ -2,12 +2,19 @@
|
|||||||
|
|
||||||
import { useParams, usePathname, useSearchParams } from "next/navigation";
|
import { useParams, usePathname, useSearchParams } from "next/navigation";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { useLocation } from "react-router-dom";
|
||||||
|
|
||||||
import { uuid } from "@/core/utils/uuid";
|
import { uuid } from "@/core/utils/uuid";
|
||||||
|
|
||||||
export function useThreadChat() {
|
export function useThreadChat() {
|
||||||
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
|
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
|
||||||
const pathname = usePathname();
|
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 searchParams = useSearchParams();
|
||||||
const [threadId, setThreadId] = useState(() => {
|
const [threadId, setThreadId] = useState(() => {
|
||||||
@@ -37,7 +44,7 @@ export function useThreadChat() {
|
|||||||
}
|
}
|
||||||
setIsNewThread(false);
|
setIsNewThread(false);
|
||||||
setThreadId(threadIdFromPath);
|
setThreadId(threadIdFromPath);
|
||||||
}, [pathname, threadIdFromPath]);
|
}, [pathname, threadIdFromPath, locationKey]);
|
||||||
const isMock = searchParams.get("mock") === "true";
|
const isMock = searchParams.get("mock") === "true";
|
||||||
return { threadId, setThreadId, isNewThread, setIsNewThread, isMock };
|
return { threadId, setThreadId, isNewThread, setIsNewThread, isMock };
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
import type { ChatStatus } from "ai";
|
import type { ChatStatus } from "ai";
|
||||||
import {
|
import {
|
||||||
BrainCircuitIcon,
|
BrainCircuitIcon,
|
||||||
BookMarkedIcon,
|
BookMarkedIcon,
|
||||||
CheckIcon,
|
CheckIcon,
|
||||||
FileTextIcon,
|
FileTextIcon,
|
||||||
GraduationCapIcon,
|
GraduationCapIcon,
|
||||||
LightbulbIcon,
|
LightbulbIcon,
|
||||||
@@ -86,8 +86,8 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "../ui/dropdown-menu";
|
} from "../ui/dropdown-menu";
|
||||||
|
|
||||||
import { useRecommendedQuestions } from "@/core/recommended-questions/hooks";
|
import { useRecommendedQuestions } from "@/core/recommended-questions/hooks";
|
||||||
import { useLocalSettings } from "@/core/settings";
|
import { useLocalSettings } from "@/core/settings";
|
||||||
|
|
||||||
|
|
||||||
import { useThread } from "./messages/context";
|
import { useThread } from "./messages/context";
|
||||||
@@ -178,8 +178,8 @@ export function InputBox({
|
|||||||
onAgentChange: (agentId: string | null) => void;
|
onAgentChange: (agentId: string | null) => void;
|
||||||
};
|
};
|
||||||
}) {
|
}) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const [localSettings, setLocalSettings] = useLocalSettings();
|
const [localSettings, setLocalSettings] = useLocalSettings();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||||
const { models } = useModels();
|
const { models } = useModels();
|
||||||
@@ -292,18 +292,18 @@ export function InputBox({
|
|||||||
});
|
});
|
||||||
}, [context, onContextChange]);
|
}, [context, onContextChange]);
|
||||||
|
|
||||||
const memoryInjectionEnabled = context.memory_injection_enabled ?? true;
|
const memoryInjectionEnabled = context.memory_injection_enabled ?? true;
|
||||||
const handleMemoryInjectionToggle = useCallback(() => {
|
const handleMemoryInjectionToggle = useCallback(() => {
|
||||||
onContextChange?.({
|
onContextChange?.({
|
||||||
...context,
|
...context,
|
||||||
memory_injection_enabled: !memoryInjectionEnabled,
|
memory_injection_enabled: !memoryInjectionEnabled,
|
||||||
});
|
});
|
||||||
}, [context, memoryInjectionEnabled, onContextChange]);
|
}, [context, memoryInjectionEnabled, onContextChange]);
|
||||||
|
|
||||||
const ragModeEnabled = localSettings.display.ragModeEnabled;
|
const ragModeEnabled = localSettings.display.ragModeEnabled;
|
||||||
const handleRagModeToggle = useCallback(() => {
|
const handleRagModeToggle = useCallback(() => {
|
||||||
setLocalSettings("display", { ragModeEnabled: !ragModeEnabled });
|
setLocalSettings("display", { ragModeEnabled: !ragModeEnabled });
|
||||||
}, [ragModeEnabled, setLocalSettings]);
|
}, [ragModeEnabled, setLocalSettings]);
|
||||||
|
|
||||||
const handleSubmit = useCallback(
|
const handleSubmit = useCallback(
|
||||||
async (message: PromptInputMessage) => {
|
async (message: PromptInputMessage) => {
|
||||||
@@ -629,28 +629,33 @@ export function InputBox({
|
|||||||
<BrainCircuitIcon className="size-3" />
|
<BrainCircuitIcon className="size-3" />
|
||||||
<span className="text-xs font-normal">记忆</span>
|
<span className="text-xs font-normal">记忆</span>
|
||||||
</PromptInputButton>
|
</PromptInputButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<Tooltip
|
<Tooltip
|
||||||
content={
|
content={
|
||||||
ragModeEnabled
|
ragModeEnabled
|
||||||
? "参考文献模式已开启:检索类结果会按编号引用展示"
|
? "参考文献模式已开启:检索类结果会按编号引用展示"
|
||||||
: "参考文献模式已关闭:技能配置的引用展示不会生效"
|
: "参考文献模式已关闭:点击开启"
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<PromptInputButton
|
<PromptInputButton
|
||||||
className={cn(
|
type="button"
|
||||||
"gap-1.5! rounded-full px-3! shadow-none",
|
aria-pressed={ragModeEnabled}
|
||||||
ragModeEnabled
|
className={cn(
|
||||||
? "border border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
|
"gap-1.5! rounded-full px-3! shadow-none",
|
||||||
: "border-0 bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
|
ragModeEnabled
|
||||||
)}
|
? "border border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
|
||||||
onClick={handleRagModeToggle}
|
: "border-0 bg-transparent text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
|
||||||
>
|
)}
|
||||||
<BookMarkedIcon className="size-3" />
|
onClick={handleRagModeToggle}
|
||||||
<span className="text-xs font-normal">参考文献</span>
|
>
|
||||||
</PromptInputButton>
|
{ragModeEnabled && (
|
||||||
</Tooltip>
|
<CheckIcon className="size-3 text-emerald-700 dark:text-emerald-200" />
|
||||||
<PromptInputActionMenu>
|
)}
|
||||||
|
<BookMarkedIcon className="size-3" />
|
||||||
|
<span className="text-xs font-normal">参考文献</span>
|
||||||
|
</PromptInputButton>
|
||||||
|
</Tooltip>
|
||||||
|
<PromptInputActionMenu>
|
||||||
<ModeHoverGuide
|
<ModeHoverGuide
|
||||||
mode={
|
mode={
|
||||||
context.mode === "flash" ||
|
context.mode === "flash" ||
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
SidebarGroup,
|
SidebarGroup,
|
||||||
@@ -38,6 +39,21 @@ export function WorkspaceNavChatList({
|
|||||||
}) {
|
}) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
// 「新对话」点击时,如果已经在 /chats/new 路径,直接 navigate 会被 react-router
|
||||||
|
// 当成同路径 no-op,不更新 location.key,挂在 location.key 上的下游 hook
|
||||||
|
// (useThreadChat)就感知不到「用户想重开一个对话」,UI 不刷新。
|
||||||
|
// 这里显式拦截:同路径时用 replace + 强制生成新 location.key 的方式重置。
|
||||||
|
const handleNewChatClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
|
||||||
|
if (event.metaKey || event.ctrlKey || event.shiftKey || event.button === 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
navigate("/page/workspace/chats/new", {
|
||||||
|
replace: true,
|
||||||
|
state: { resetAt: Date.now() },
|
||||||
|
});
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SidebarGroup className={cn("px-2", showCollapseTrigger ? "pt-3" : "pt-2")}>
|
<SidebarGroup className={cn("px-2", showCollapseTrigger ? "pt-3" : "pt-2")}>
|
||||||
@@ -49,7 +65,7 @@ export function WorkspaceNavChatList({
|
|||||||
asChild
|
asChild
|
||||||
className={cn(NEW_CHAT_CLASS, showCollapseTrigger && "min-w-0 flex-1")}
|
className={cn(NEW_CHAT_CLASS, showCollapseTrigger && "min-w-0 flex-1")}
|
||||||
>
|
>
|
||||||
<Link href="/page/workspace/chats/new">
|
<Link href="/page/workspace/chats/new" onClick={handleNewChatClick}>
|
||||||
<MessageSquarePlus />
|
<MessageSquarePlus />
|
||||||
<span>{t.sidebar.newChat}</span>
|
<span>{t.sidebar.newChat}</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ export const DEFAULT_LOCAL_SETTINGS: LocalSettings = {
|
|||||||
notification: {
|
notification: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
},
|
},
|
||||||
display: {
|
display: {
|
||||||
streamSpeedMeterEnabled: true,
|
streamSpeedMeterEnabled: true,
|
||||||
ragModeEnabled: true,
|
ragModeEnabled: false,
|
||||||
},
|
},
|
||||||
context: {
|
context: {
|
||||||
model_name: undefined,
|
model_name: undefined,
|
||||||
mode: undefined,
|
mode: undefined,
|
||||||
@@ -33,13 +33,13 @@ export interface LocalSettings {
|
|||||||
* AI reply is in flight. Default on; controlled by the user from
|
* AI reply is in flight. Default on; controlled by the user from
|
||||||
* the appearance settings page.
|
* the appearance settings page.
|
||||||
*/
|
*/
|
||||||
streamSpeedMeterEnabled: boolean;
|
streamSpeedMeterEnabled: boolean;
|
||||||
/**
|
/**
|
||||||
* Global switch for skill result display adapters. When disabled, chat
|
* Global switch for skill result display adapters. When disabled, chat
|
||||||
* messages render tool results with the legacy generic search UI only.
|
* messages render tool results with the legacy generic search UI only.
|
||||||
*/
|
*/
|
||||||
ragModeEnabled: boolean;
|
ragModeEnabled: boolean;
|
||||||
};
|
};
|
||||||
context: Omit<
|
context: Omit<
|
||||||
AgentThreadContext,
|
AgentThreadContext,
|
||||||
| "thread_id"
|
| "thread_id"
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ import { apiFetch } from "../api";
|
|||||||
import { getBackendBaseURL } from "../config";
|
import { getBackendBaseURL } from "../config";
|
||||||
import { useI18n } from "../i18n/hooks";
|
import { useI18n } from "../i18n/hooks";
|
||||||
import type { FileInMessage } from "../messages/utils";
|
import type { FileInMessage } from "../messages/utils";
|
||||||
import type { LocalSettings } from "../settings";
|
import type { LocalSettings } from "../settings";
|
||||||
import { useLocalSettings } from "../settings";
|
import { useLocalSettings } from "../settings";
|
||||||
import { useUpdateSubtask } from "../tasks/context";
|
import { useUpdateSubtask } from "../tasks/context";
|
||||||
import type { UploadedFileInfo } from "../uploads";
|
import type { UploadedFileInfo } from "../uploads";
|
||||||
import { promptInputFilePartToFile, uploadFiles } from "../uploads";
|
import { promptInputFilePartToFile, uploadFiles } from "../uploads";
|
||||||
@@ -146,8 +146,8 @@ export function useThreadStream({
|
|||||||
onFinish,
|
onFinish,
|
||||||
onToolEnd,
|
onToolEnd,
|
||||||
}: ThreadStreamOptions) {
|
}: ThreadStreamOptions) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const [localSettings] = useLocalSettings();
|
const [localSettings] = useLocalSettings();
|
||||||
// Track the thread ID that is currently streaming to handle thread changes during streaming
|
// Track the thread ID that is currently streaming to handle thread changes during streaming
|
||||||
const [onStreamThreadId, setOnStreamThreadId] = useState(() => threadId);
|
const [onStreamThreadId, setOnStreamThreadId] = useState(() => threadId);
|
||||||
// Ref to track current thread ID across async callbacks without causing re-renders,
|
// Ref to track current thread ID across async callbacks without causing re-renders,
|
||||||
@@ -309,9 +309,27 @@ export function useThreadStream({
|
|||||||
// Track message count before sending so we know when server has responded
|
// Track message count before sending so we know when server has responded
|
||||||
const prevMsgCountRef = useRef(thread.messages.length);
|
const prevMsgCountRef = useRef(thread.messages.length);
|
||||||
|
|
||||||
|
// Keep a ref to the latest `thread` so the threadId-change effect can stop
|
||||||
|
// an in-flight stream without re-running on every render that produces a
|
||||||
|
// new `thread` identity.
|
||||||
|
const threadStreamRef = useRef(thread);
|
||||||
|
threadStreamRef.current = thread;
|
||||||
|
|
||||||
// Reset thread-local pending UI state when switching between threads so
|
// Reset thread-local pending UI state when switching between threads so
|
||||||
// optimistic messages and in-flight guards do not leak across chat views.
|
// optimistic messages and in-flight guards do not leak across chat views.
|
||||||
|
// Also abort any in-flight SSE from the previous thread: without this,
|
||||||
|
// clicking "新对话" mid-stream leaves the old run firing onUpdate events
|
||||||
|
// against the now-detached thread context, which manifests as the page
|
||||||
|
// appearing unresponsive to the navigation.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
const prevThread = threadStreamRef.current;
|
||||||
|
if (prevThread?.isLoading) {
|
||||||
|
try {
|
||||||
|
prevThread.stop();
|
||||||
|
} catch {
|
||||||
|
// best-effort; nothing useful to do if the SDK fails to abort
|
||||||
|
}
|
||||||
|
}
|
||||||
startedRef.current = false;
|
startedRef.current = false;
|
||||||
sendInFlightRef.current = false;
|
sendInFlightRef.current = false;
|
||||||
prevMsgCountRef.current = 0;
|
prevMsgCountRef.current = 0;
|
||||||
@@ -508,9 +526,9 @@ export function useThreadStream({
|
|||||||
: context.mode === "thinking"
|
: context.mode === "thinking"
|
||||||
? "low"
|
? "low"
|
||||||
: undefined),
|
: undefined),
|
||||||
memory_injection_enabled: context.memory_injection_enabled ?? true,
|
memory_injection_enabled: context.memory_injection_enabled ?? true,
|
||||||
rag_mode_enabled: localSettings.display.ragModeEnabled,
|
rag_mode_enabled: localSettings.display.ragModeEnabled,
|
||||||
thread_id: threadId,
|
thread_id: threadId,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -523,8 +541,8 @@ export function useThreadStream({
|
|||||||
sendInFlightRef.current = false;
|
sendInFlightRef.current = false;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[thread, _handleOnStart, t.uploads.uploadingFiles, context, localSettings.display.ragModeEnabled, queryClient],
|
[thread, _handleOnStart, t.uploads.uploadingFiles, context, localSettings.display.ragModeEnabled, queryClient],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Merge thread with optimistic messages for display
|
// Merge thread with optimistic messages for display
|
||||||
const mergedThread =
|
const mergedThread =
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { CSSProperties, ReactNode } from "react";
|
import type { CSSProperties, ReactNode } from "react";
|
||||||
import { Navigate, Route, Routes } from "react-router-dom";
|
import { Navigate, Route, Routes, useLocation } from "react-router-dom";
|
||||||
|
|
||||||
import { getStoredAuth } from "@/core/auth";
|
import { getStoredAuth } from "@/core/auth";
|
||||||
|
|
||||||
@@ -89,6 +89,20 @@ export function ChatRuntime({ children }: { children: ReactNode }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 让 ChatPage 在每次真正的 react-router navigation 上完整 remount。
|
||||||
|
*
|
||||||
|
* 背景:点「新对话」时即使路径不变,我们也会用 `navigate(..., { replace: true,
|
||||||
|
* state: { resetAt } })` 强制刷新 location.key —— 用它作 key 能保证 useStream、
|
||||||
|
* useThreadStream、optimistic state、refs 一次性全部丢弃,避免上一条流的
|
||||||
|
* `stream.values` 残留把欢迎页底下的旧消息拖出来(SDK 的 stream.clear() 需要
|
||||||
|
* 多次 effect tick 才会清干净,中间过渡帧用户能看见)。
|
||||||
|
*/
|
||||||
|
function KeyedChatPage({ render }: { render: () => ReactNode }) {
|
||||||
|
const key = useLocation().key;
|
||||||
|
return <ChatRuntime key={key}>{render()}</ChatRuntime>;
|
||||||
|
}
|
||||||
|
|
||||||
export default function WorkspaceRoutes({
|
export default function WorkspaceRoutes({
|
||||||
pageSidebarCollapsed = false,
|
pageSidebarCollapsed = false,
|
||||||
pageSidebarHidden = false,
|
pageSidebarHidden = false,
|
||||||
@@ -123,9 +137,7 @@ export default function WorkspaceRoutes({
|
|||||||
path="chats/:thread_id"
|
path="chats/:thread_id"
|
||||||
element={
|
element={
|
||||||
<WorkspaceLayout {...layoutProps}>
|
<WorkspaceLayout {...layoutProps}>
|
||||||
<ChatRuntime>
|
<KeyedChatPage render={() => <ChatPage />} />
|
||||||
<ChatPage />
|
|
||||||
</ChatRuntime>
|
|
||||||
</WorkspaceLayout>
|
</WorkspaceLayout>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|||||||
Reference in new issue
Block a user