fix(assistant-chat): prevent stale history response from resetting selected conversation

This commit is contained in:
2026-02-24 13:27:09 +03:00
parent 286167b1d5
commit 2e93f5ca63

View File

@@ -56,6 +56,7 @@
let archivedConversationsTotal = 0; let archivedConversationsTotal = 0;
let historyPage = 1; let historyPage = 1;
let historyHasNext = false; let historyHasNext = false;
let historyLoadVersion = 0;
let conversationsPage = 1; let conversationsPage = 1;
let conversationsHasNext = false; let conversationsHasNext = false;
let historyViewport = null; let historyViewport = null;
@@ -71,18 +72,22 @@
* @POST: messages are populated from persisted history and conversation id is synchronized. * @POST: messages are populated from persisted history and conversation id is synchronized.
* @SIDE_EFFECT: Performs API call to assistant history endpoint. * @SIDE_EFFECT: Performs API call to assistant history endpoint.
*/ */
async function loadHistory() { async function loadHistory(targetConversationId = conversationId) {
if (loadingHistory || !isOpen) return; if (loadingHistory || !isOpen) return;
const requestVersion = ++historyLoadVersion;
loadingHistory = true; loadingHistory = true;
try { try {
const history = await getAssistantHistory(1, HISTORY_PAGE_SIZE, conversationId, true); const history = await getAssistantHistory(1, HISTORY_PAGE_SIZE, targetConversationId, true);
if (requestVersion !== historyLoadVersion) {
return;
}
messages = (history.items || []).map((msg) => ({ messages = (history.items || []).map((msg) => ({
...msg, ...msg,
actions: msg.actions || msg.metadata?.actions || [], actions: msg.actions || msg.metadata?.actions || [],
})); }));
historyPage = 1; historyPage = 1;
historyHasNext = Boolean(history.has_next); historyHasNext = Boolean(history.has_next);
if (history.conversation_id && history.conversation_id !== conversationId) { if (!targetConversationId && history.conversation_id && history.conversation_id !== conversationId) {
setAssistantConversationId(history.conversation_id); setAssistantConversationId(history.conversation_id);
} }
initialized = true; initialized = true;
@@ -286,9 +291,13 @@
async function selectConversation(conversation) { async function selectConversation(conversation) {
if (!conversation?.conversation_id) return; if (!conversation?.conversation_id) return;
if (conversation.conversation_id === conversationId) return; if (conversation.conversation_id === conversationId) return;
// Invalidate any in-flight history request to avoid stale conversation overwrite.
historyLoadVersion += 1;
setAssistantConversationId(conversation.conversation_id); setAssistantConversationId(conversation.conversation_id);
initialized = false; messages = [];
await loadHistory(); historyPage = 1;
historyHasNext = false;
await loadHistory(conversation.conversation_id);
} }
// [/DEF:selectConversation:Function] // [/DEF:selectConversation:Function]