diff --git a/src/components/chat/chatStorage.ts b/src/components/chat/chatStorage.ts index 280b996..46fc1d6 100644 --- a/src/components/chat/chatStorage.ts +++ b/src/components/chat/chatStorage.ts @@ -84,7 +84,9 @@ const compareSessionsByAnchorTime = ( return right.id.localeCompare(left.id); }; -const toLoadedChatState = (session: ChatSessionRecord | undefined): LoadedChatState => { +const toLoadedChatState = ( + session: ChatSessionRecord | undefined, +): LoadedChatState => { if (!session) return emptyLoadedChatState(); return { storageSessionId: session.id, @@ -107,7 +109,9 @@ const getDb = () => openDB(CHAT_DB_NAME, CHAT_DB_VERSION, { upgrade(db) { if (!db.objectStoreNames.contains(SESSION_STORE)) { - const sessionStore = db.createObjectStore(SESSION_STORE, { keyPath: "id" }); + const sessionStore = db.createObjectStore(SESSION_STORE, { + keyPath: "id", + }); sessionStore.createIndex("by-updatedAt", "updatedAt"); } @@ -273,13 +277,17 @@ export const saveActiveChatState = async ( const finalTitle = preferredTitle || existingSession?.title || "新对话"; const hasContentChanged = !existingSession || - serializeConversationState(existingSession) !== serializeConversationState(state); + (existingSession && serializeConversationState(existingSession)) !== + serializeConversationState(state); const shouldAnchorCreatedAtToFirstMessage = - Boolean(existingSession) && !hasChatContent(existingSession) && hasContent; + existingSession && !hasChatContent(existingSession) && hasContent; const nextRecord: ChatSessionRecord = { id: storageSessionId, title: finalTitle, - isTitleManuallyEdited: state.isTitleManuallyEdited ?? existingSession?.isTitleManuallyEdited ?? false, + isTitleManuallyEdited: + state.isTitleManuallyEdited ?? + existingSession?.isTitleManuallyEdited ?? + false, createdAt: shouldAnchorCreatedAtToFirstMessage ? now : existingSession?.createdAt ?? now, @@ -360,7 +368,9 @@ export const createEmptyChatSession = async (): Promise => { return toLoadedChatState(session); }; -export const loadChatSessionById = async (sessionId: string): Promise => { +export const loadChatSessionById = async ( + sessionId: string, +): Promise => { if (typeof window === "undefined") return emptyLoadedChatState(); await migrateLegacyLocalStorage(); @@ -380,14 +390,18 @@ export const loadChatSessionById = async (sessionId: string): Promise => { +export const deleteChatSession = async ( + sessionId: string, +): Promise => { if (typeof window === "undefined") return undefined; const db = await getDb(); await db.delete(SESSION_STORE, sessionId); const remainingSessions = await db.getAll(SESSION_STORE); - const nextActiveSession = remainingSessions.sort(compareSessionsByAnchorTime)[0]; + const nextActiveSession = remainingSessions.sort( + compareSessionsByAnchorTime, + )[0]; const meta = await getMeta(); await setMeta({