From 8627a91f6f9a18b7dd2fdac7a9586309b71c557c Mon Sep 17 00:00:00 2001 From: Nickii Miaro Date: Thu, 5 Sep 2024 19:01:19 +0300 Subject: [PATCH] fix: cached message state mixup (#3278) * fix cached message state duplication * ensure only messages in chat available * check for duplicates in delta messages --- .../mgt-chat/src/statefulClient/Caching/MessageCache.ts | 7 ++++++- .../mgt-chat/src/statefulClient/StatefulGraphChatClient.ts | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/mgt-chat/src/statefulClient/Caching/MessageCache.ts b/packages/mgt-chat/src/statefulClient/Caching/MessageCache.ts index 2efc756607..df8ab09f18 100644 --- a/packages/mgt-chat/src/statefulClient/Caching/MessageCache.ts +++ b/packages/mgt-chat/src/statefulClient/Caching/MessageCache.ts @@ -53,7 +53,12 @@ export class MessageCache { return data; } else { // need to iterate through the messages and either push or splice them into the array. - messages.forEach(m => this.addMessageToCacheData(m, cachedData)); + messages.forEach(m => { + // ensure that only new messages (those not already in the cache) are added to the cache for the specified chat + if (m.chatId === chatId && !cachedData.value.some(cachedMessage => cachedMessage.id === m.id)) { + this.addMessageToCacheData(m, cachedData); + } + }); if (updateNextLink) { cachedData.nextLink = nextLink; } diff --git a/packages/mgt-chat/src/statefulClient/StatefulGraphChatClient.ts b/packages/mgt-chat/src/statefulClient/StatefulGraphChatClient.ts index dddf3a7bac..578255787c 100644 --- a/packages/mgt-chat/src/statefulClient/StatefulGraphChatClient.ts +++ b/packages/mgt-chat/src/statefulClient/StatefulGraphChatClient.ts @@ -494,8 +494,13 @@ class StatefulGraphChatClient extends BaseStatefulClient { const deltaMessages = await this.loadDeltaData(this._chatId, cachedMessages.lastModifiedDateTime); // add delta messages to cache const updatedState = await this._cache.cacheMessages(this._chatId, deltaMessages); + // Filters the delta messages based on whether their IDs exist in the updated state. + const filteredDeltaMessages = deltaMessages.filter( + deltaMessage => + !updatedState.value.some(message => message.id === deltaMessage.id && message.chatId === deltaMessage.chatId) + ); // writeMessagesToState concats with existing state, need to be careful not to create duplicate messages - updatedState.value = deltaMessages; + updatedState.value = filteredDeltaMessages; // update state await this.writeMessagesToState(updatedState); } else {