重构聊天会话标题管理,支持首轮对话更新

This commit is contained in:
2026-05-08 17:22:54 +08:00
parent 5cfb7cc38f
commit cf43700459
2 changed files with 43 additions and 11 deletions
@@ -25,6 +25,7 @@ import {
loadActiveChatState,
loadChatSessionById,
saveActiveChatState,
updateChatSessionTitle,
} from "../chatStorage";
type UseAgentChatSessionOptions = {
@@ -110,6 +111,7 @@ export const useAgentChatSession = ({
const abortRef = useRef<AbortController | null>(null);
const sessionIdRef = useRef<string | undefined>(undefined);
const cancelPromiseRef = useRef<Promise<void> | null>(null);
const titleUpdateNonceRef = useRef(0);
useEffect(() => {
sessionIdRef.current = sessionId;
@@ -130,6 +132,7 @@ export const useAgentChatSession = ({
sessionIdRef.current = loadedState.sessionId;
hydrationCompletedRef.current = true;
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
setMessages(loadedState.messages);
setSessionTitle(loadedState.title);
@@ -308,6 +311,19 @@ export const useAgentChatSession = ({
const nextTitle = event.title.trim();
if (nextTitle) {
setSessionTitle(nextTitle);
const currentStorageSessionId = storageSessionIdRef.current;
if (currentStorageSessionId) {
const currentNonce = ++titleUpdateNonceRef.current;
void updateChatSessionTitle(currentStorageSessionId, nextTitle)
.then(() => listChatSessions())
.then((sessions) => {
if (titleUpdateNonceRef.current !== currentNonce) return;
setChatSessions(sessions);
})
.catch((error) => {
console.error("[GlobalChatbox] Failed to persist session title:", error);
});
}
}
} else if (event.type === "done") {
setMessages((prev) =>
@@ -431,6 +447,7 @@ export const useAgentChatSession = ({
setSessionId(undefined);
sessionIdRef.current = undefined;
storageSessionIdRef.current = undefined;
titleUpdateNonceRef.current += 1;
setIsStreaming(false);
}, []);
@@ -445,6 +462,7 @@ export const useAgentChatSession = ({
const sessions = await listChatSessions();
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
storageSessionIdRef.current = newState.storageSessionId;
sessionIdRef.current = newState.sessionId;
setMessages(newState.messages);
@@ -469,6 +487,7 @@ export const useAgentChatSession = ({
]);
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
storageSessionIdRef.current = nextState.storageSessionId;
sessionIdRef.current = nextState.sessionId;
setBranchTransition(null);
@@ -501,6 +520,7 @@ export const useAgentChatSession = ({
if (!nextActiveSessionId) {
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
storageSessionIdRef.current = undefined;
sessionIdRef.current = undefined;
setBranchTransition(null);
@@ -517,6 +537,7 @@ export const useAgentChatSession = ({
listChatSessions(),
]);
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
storageSessionIdRef.current = nextState.storageSessionId;
sessionIdRef.current = nextState.sessionId;
setBranchTransition(null);