fix(chat-turnero): prevent messages mixing between contacts on fast switching

Capture activeUserId at the start of each async function (fetchMessages,
loadMoreMessages, pollMessages) and discard the response if the user changed
contacts while the request was in-flight.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-07-03 08:19:52 -05:00
co-authored by Claude Sonnet 4.6
parent a0979e31e7
commit 17703f0157
+12 -5
View File
@@ -525,10 +525,12 @@ function closeChatMobile() {
// ── Mensajes ──────────────────────────────────────────────────────────────────
async function fetchMessages() {
if (!state.activeUserId) return;
const url = BASE + API_MESSAGES + '?user_id=' + state.activeUserId + '&limit=50';
const forUser = state.activeUserId; // captura antes del await
const url = BASE + API_MESSAGES + '?user_id=' + forUser + '&limit=50';
try {
const res = await fetch(url);
const json = await res.json();
if (forUser !== state.activeUserId) return; // usuario cambió mientras esperaba
if (!json.success) return;
state.messages = json.data;
state.hasMore = json.has_more;
@@ -541,14 +543,16 @@ async function fetchMessages() {
async function loadMoreMessages() {
if (!state.activeUserId || !state.earliest) return;
const forUser = state.activeUserId;
const url = BASE + API_MESSAGES
+ '?user_id=' + state.activeUserId
+ '?user_id=' + forUser
+ '&limit=50'
+ '&before=' + encodeURIComponent(state.earliest)
+ (state.earliestId ? '&before_id=' + state.earliestId : '');
try {
const res = await fetch(url);
const json = await res.json();
if (forUser !== state.activeUserId) return;
if (!json.success || !json.data.length) {
document.getElementById('loadMoreBtn').style.display = 'none';
return;
@@ -563,13 +567,16 @@ async function loadMoreMessages() {
async function pollMessages() {
if (!state.activeUserId || !state.lastPollTime) return;
const forUser = state.activeUserId;
const sinceTime = state.lastPollTime;
const url = BASE + API_MESSAGES
+ '?user_id=' + state.activeUserId
+ '?user_id=' + forUser
+ '&limit=50'
+ '&since=' + encodeURIComponent(state.lastPollTime);
+ '&since=' + encodeURIComponent(sinceTime);
try {
const res = await fetch(url);
const json = await res.json();
if (forUser !== state.activeUserId) return; // usuario cambió mientras esperaba
if (!json.success || !json.data.length) return;
json.data.forEach(m => {
if (!state.messages.find(x => x.id === m.id)) {
@@ -578,7 +585,7 @@ async function pollMessages() {
}
});
state.lastPollTime = json.data[json.data.length - 1].created_at;
markRead(state.activeUserId);
markRead(forUser);
loadContacts(document.getElementById('searchInput').value.trim(), true);
} catch(e) {}
}