fix: 历史记录分页 — 会话丢失导致数据不完整
问题根因: 1. startNewSession() 未保存当前会话 → 点「新建会话」时旧会话丢失 2. 用户消息发送后未立即保存 → 刷新/关闭页面丢失对话 3. 通用错误处理中 saveCurrentSession() 缺少 await 修复: - startNewSession: 新建前先保存当前会话(有消息时) - sendMessage: 发送用户消息后立即 saveCurrentSession - catch 块中 saveCurrentSession 补上 await
This commit is contained in:
@@ -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();
|
const session = createNewSession();
|
||||||
state.set(KEYS.CURRENT_SESSION, session);
|
state.set(KEYS.CURRENT_SESSION, session);
|
||||||
state.set(KEYS.IS_HISTORY_VIEW, false);
|
state.set(KEYS.IS_HISTORY_VIEW, false);
|
||||||
|
|||||||
@@ -174,6 +174,9 @@ export async function sendMessage() {
|
|||||||
msgsToAdd.forEach(m => currentSession.messages.push(m));
|
msgsToAdd.forEach(m => currentSession.messages.push(m));
|
||||||
renderMessages();
|
renderMessages();
|
||||||
|
|
||||||
|
// 立即保存(防止新建会话或刷新时丢失用户消息)
|
||||||
|
await saveCurrentSession();
|
||||||
|
|
||||||
// 清空输入
|
// 清空输入
|
||||||
chatInputEl.value = '';
|
chatInputEl.value = '';
|
||||||
pendingImages = [];
|
pendingImages = [];
|
||||||
@@ -307,7 +310,7 @@ export async function sendMessage() {
|
|||||||
currentSession.messages.push(partialMsg);
|
currentSession.messages.push(partialMsg);
|
||||||
const contentDiv = placeholder?.querySelector('.msg-content');
|
const contentDiv = placeholder?.querySelector('.msg-content');
|
||||||
if (contentDiv) contentDiv.innerHTML = `<p>${existingContent}</p><p><code>[已中断]</code></p>`;
|
if (contentDiv) contentDiv.innerHTML = `<p>${existingContent}</p><p><code>[已中断]</code></p>`;
|
||||||
saveCurrentSession();
|
await saveCurrentSession();
|
||||||
} else {
|
} else {
|
||||||
if (placeholder) placeholder.remove();
|
if (placeholder) placeholder.remove();
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user