重构聊天会话标题管理,支持首轮对话更新
This commit is contained in:
@@ -68,14 +68,6 @@ const toSessionSummary = (session: ChatSessionRecord): ChatSessionSummary => ({
|
||||
updatedAt: session.updatedAt,
|
||||
});
|
||||
|
||||
const buildSessionTitle = (messages: Message[]) => {
|
||||
const firstUserMessage = messages.find((message) => message.role === "user");
|
||||
if (!firstUserMessage) return "新对话";
|
||||
const title = firstUserMessage.content.replace(/\s+/g, " ").trim();
|
||||
if (!title) return "新对话";
|
||||
return title.length > 24 ? `${title.slice(0, 24)}...` : title;
|
||||
};
|
||||
|
||||
const getDb = () =>
|
||||
openDB<ChatDB>(CHAT_DB_NAME, CHAT_DB_VERSION, {
|
||||
upgrade(db) {
|
||||
@@ -170,7 +162,7 @@ const migrateLegacyLocalStorage = async () => {
|
||||
const now = Date.now();
|
||||
const sessionRecord: ChatSessionRecord = {
|
||||
id: createId(),
|
||||
title: buildSessionTitle(legacyState.messages),
|
||||
title: "新对话",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
sessionId: legacyState.sessionId,
|
||||
@@ -244,9 +236,8 @@ export const saveActiveChatState = async (
|
||||
|
||||
const now = Date.now();
|
||||
const storageSessionId = state.storageSessionId ?? createId();
|
||||
const computedTitle = buildSessionTitle(state.messages);
|
||||
const preferredTitle = state.title?.trim();
|
||||
const finalTitle = preferredTitle || computedTitle;
|
||||
const finalTitle = preferredTitle || existingSession?.title || "新对话";
|
||||
const nextRecord: ChatSessionRecord = {
|
||||
id: storageSessionId,
|
||||
title: finalTitle,
|
||||
@@ -278,6 +269,26 @@ export const listChatSessions = async (): Promise<ChatSessionSummary[]> => {
|
||||
.map(toSessionSummary);
|
||||
};
|
||||
|
||||
export const updateChatSessionTitle = async (
|
||||
storageSessionId: string,
|
||||
title: string,
|
||||
): Promise<void> => {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const normalizedTitle = title.trim();
|
||||
if (!normalizedTitle) return;
|
||||
|
||||
const db = await getDb();
|
||||
const session = await db.get(SESSION_STORE, storageSessionId);
|
||||
if (!session) return;
|
||||
|
||||
await db.put(SESSION_STORE, {
|
||||
...session,
|
||||
title: normalizedTitle,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
};
|
||||
|
||||
export const createEmptyChatSession = async (): Promise<LoadedChatState> => {
|
||||
if (typeof window === "undefined") return emptyLoadedChatState();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user