fix: 历史记录分页 — 会话丢失导致数据不完整

问题根因:
1. startNewSession() 未保存当前会话 → 点「新建会话」时旧会话丢失
2. 用户消息发送后未立即保存 → 刷新/关闭页面丢失对话
3. 通用错误处理中 saveCurrentSession() 缺少 await

修复:
- startNewSession: 新建前先保存当前会话(有消息时)
- sendMessage: 发送用户消息后立即 saveCurrentSession
- catch 块中 saveCurrentSession 补上 await
This commit is contained in:
thzxx
2026-04-03 12:39:59 +08:00
parent 27317f4d32
commit eb04a6baa8
2 changed files with 13 additions and 2 deletions
+9 -1
View File
@@ -33,7 +33,15 @@ function createNewSession() {
};
}
function startNewSession() {
async function startNewSession() {
// 先保存当前会话(如果有的话)
const db = state.get(KEYS.DB);
const currentSession = state.get(KEYS.CURRENT_SESSION);
if (db && currentSession && currentSession.messages.length > 0) {
currentSession.updatedAt = Date.now();
await db.saveSession(currentSession);
}
const session = createNewSession();
state.set(KEYS.CURRENT_SESSION, session);
state.set(KEYS.IS_HISTORY_VIEW, false);
+4 -1
View File
@@ -174,6 +174,9 @@ export async function sendMessage() {
msgsToAdd.forEach(m => currentSession.messages.push(m));
renderMessages();
// 立即保存(防止新建会话或刷新时丢失用户消息)
await saveCurrentSession();
// 清空输入
chatInputEl.value = '';
pendingImages = [];
@@ -307,7 +310,7 @@ export async function sendMessage() {
currentSession.messages.push(partialMsg);
const contentDiv = placeholder?.querySelector('.msg-content');
if (contentDiv) contentDiv.innerHTML = `<p>${existingContent}</p><p><code>[已中断]</code></p>`;
saveCurrentSession();
await saveCurrentSession();
} else {
if (placeholder) placeholder.remove();
}