refactor(chat): remove frontend state saves

This commit is contained in:
2026-06-10 19:29:45 +08:00
parent 9c0a7a2864
commit e2a6bb0e7d
6 changed files with 112 additions and 255 deletions
@@ -4,10 +4,10 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { abortAgentChat, forkAgentChat, rejectAgentQuestion, replyAgentPermission, replyAgentQuestion, resumeAgentChatStream, streamAgentChat } from "@/lib/chatStream";
import type { PermissionReply, StreamEvent } from "@/lib/chatStream";
import type { AgentArtifact, ChatSessionSummary, LoadedChatState, Message } from "../GlobalChatbox.types";
import type { AgentArtifact, ChatSessionSummary, Message } from "../GlobalChatbox.types";
import { cloneMessages } from "../GlobalChatbox.utils";
import { createEmptyChatState, deleteChatSession, listChatSessions, loadChatSessionById, saveActiveChatState, updateChatSessionTitle } from "../chatStorage";
import { applyQuestionResponse, cancelRunningTodos, completeRunningProgress, createAssistantMessage, createPersistedStateKey, createTodoUpdateFromEvent, createUserMessage, dedupeQuestionsAcrossMessages, finalizeAssistantMessageAfterAbort, normalizeSessionTodos, toPermissionStatus, upsertPermission, upsertProgress, upsertQuestionAcrossMessages } from "./agentChatSessionState";
import { createEmptyChatState, deleteChatSession, listChatSessions, loadChatSessionById, updateChatSessionTitle } from "../chatStorage";
import { applyQuestionResponse, cancelRunningTodos, completeRunningProgress, createAssistantMessage, createTodoUpdateFromEvent, createUserMessage, dedupeQuestionsAcrossMessages, finalizeAssistantMessageAfterAbort, normalizeSessionTodos, toPermissionStatus, upsertPermission, upsertProgress, upsertQuestionAcrossMessages } from "./agentChatSessionState";
import type { PromptRunOptions, UseAgentChatSessionOptions } from "./useAgentChatSession.types";
export const useAgentChatSession = ({
@@ -17,7 +17,6 @@ export const useAgentChatSession = ({
getModel,
getApprovalMode,
}: UseAgentChatSessionOptions) => {
const hydrationCompletedRef = useRef(false);
const hydrationNonceRef = useRef(0);
const [messages, setMessages] = useState<Message[]>([]);
@@ -35,14 +34,6 @@ export const useAgentChatSession = ({
const isSessionTitleManuallyEditedRef = useRef(false);
const cancelPromiseRef = useRef<Promise<void> | null>(null);
const titleUpdateNonceRef = useRef(0);
const lastPersistedStateKeyRef = useRef(
createPersistedStateKey({
sessionId: undefined,
title: undefined,
isTitleManuallyEdited: false,
messages: [],
}),
);
useEffect(() => {
sessionIdRef.current = sessionId;
@@ -62,17 +53,9 @@ export const useAgentChatSession = ({
const hydrate = async () => {
setIsHydrating(true);
hydrationCompletedRef.current = false;
if (!projectId) {
sessionIdRef.current = undefined;
lastPersistedStateKeyRef.current = createPersistedStateKey({
title: undefined,
isTitleManuallyEdited: false,
messages: [],
sessionId: undefined,
});
hydrationCompletedRef.current = true;
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
setMessages([]);
@@ -93,8 +76,6 @@ export const useAgentChatSession = ({
if (cancelled) return;
sessionIdRef.current = loadedState.sessionId;
lastPersistedStateKeyRef.current = createPersistedStateKey(loadedState);
hydrationCompletedRef.current = true;
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
@@ -127,51 +108,6 @@ export const useAgentChatSession = ({
};
}, [projectId]);
useEffect(() => {
if (!projectId || isHydrating || !hydrationCompletedRef.current) return;
const currentHydrationNonce = hydrationNonceRef.current;
const persistTimer = window.setTimeout(() => {
if (isStreaming) {
return;
}
const state: LoadedChatState = {
title: sessionTitle,
isTitleManuallyEdited: isSessionTitleManuallyEdited,
messages,
sessionId,
};
const currentStateKey = createPersistedStateKey(state);
if (currentStateKey === lastPersistedStateKeyRef.current) {
return;
}
void saveActiveChatState(state)
.then((sessionId) => {
if (hydrationNonceRef.current !== currentHydrationNonce) return;
sessionIdRef.current = sessionId;
lastPersistedStateKeyRef.current = createPersistedStateKey({
...state,
sessionId,
});
return listChatSessions();
})
.then((sessions) => {
if (!sessions || hydrationNonceRef.current !== currentHydrationNonce) return;
setChatSessions(sessions);
})
.catch((error) => {
console.error("[GlobalChatbox] Failed to persist chat state:", error);
});
}, 150);
return () => {
window.clearTimeout(persistTimer);
};
}, [isHydrating, isSessionTitleManuallyEdited, isStreaming, messages, projectId, sessionId, sessionTitle]);
const appendArtifact = useCallback((messageId: string, artifact: AgentArtifact) => {
setMessages((prev) =>
prev.map((message) =>
@@ -226,12 +162,6 @@ export const useAgentChatSession = ({
const targetSessionId = event.sessionId || currentSessionId;
if (targetSessionId === currentSessionId) {
setSessionTitle(nextTitle);
lastPersistedStateKeyRef.current = createPersistedStateKey({
sessionId: targetSessionId,
title: nextTitle,
isTitleManuallyEdited: false,
messages: messagesRef.current,
});
}
if (targetSessionId) {
const currentNonce = ++titleUpdateNonceRef.current;
@@ -743,12 +673,6 @@ export const useAgentChatSession = ({
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
sessionIdRef.current = undefined;
lastPersistedStateKeyRef.current = createPersistedStateKey({
title: "新对话",
isTitleManuallyEdited: false,
messages: [],
sessionId: undefined,
});
setMessages([]);
setSessionTitle("新对话");
setIsSessionTitleManuallyEdited(false);
@@ -777,7 +701,6 @@ export const useAgentChatSession = ({
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
sessionIdRef.current = nextState.sessionId;
lastPersistedStateKeyRef.current = createPersistedStateKey(nextState);
setMessages(nextState.messages);
setSessionTitle(nextState.title);
setIsSessionTitleManuallyEdited(nextState.isTitleManuallyEdited ?? false);
@@ -821,12 +744,6 @@ export const useAgentChatSession = ({
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
sessionIdRef.current = undefined;
lastPersistedStateKeyRef.current = createPersistedStateKey({
title: undefined,
isTitleManuallyEdited: false,
messages: [],
sessionId: undefined,
});
setMessages([]);
setSessionTitle(undefined);
setIsSessionTitleManuallyEdited(false);
@@ -842,7 +759,6 @@ export const useAgentChatSession = ({
hydrationNonceRef.current += 1;
titleUpdateNonceRef.current += 1;
sessionIdRef.current = nextState.sessionId;
lastPersistedStateKeyRef.current = createPersistedStateKey(nextState);
setMessages(nextState.messages);
setSessionTitle(nextState.title);
setIsSessionTitleManuallyEdited(nextState.isTitleManuallyEdited ?? false);
@@ -884,18 +800,12 @@ export const useAgentChatSession = ({
if (sessionIdRef.current === targetSessionId) {
setSessionTitle(normalizedTitle);
setIsSessionTitleManuallyEdited(true);
lastPersistedStateKeyRef.current = createPersistedStateKey({
sessionId: targetSessionId,
title: normalizedTitle,
isTitleManuallyEdited: true,
messages,
});
}
} catch (error) {
console.error("[GlobalChatbox] Failed to rename chat session:", error);
}
},
[isHydrating, messages],
[isHydrating],
);
const createBranch = useCallback(
@@ -920,12 +830,6 @@ export const useAgentChatSession = ({
const forkTitle = sessionTitle ? `${sessionTitle} 副本` : "新对话副本";
setSessionTitle(forkTitle);
try {
await saveActiveChatState({
title: forkTitle,
isTitleManuallyEdited: false,
messages: copiedMessages,
sessionId: forkedSessionId,
});
setChatSessions(await listChatSessions());
} catch (error) {
console.error("[GlobalChatbox] Failed to refresh chat sessions after fork:", error);