From 256e9228f51b3e077b11de852947c319cc181e3d Mon Sep 17 00:00:00 2001 From: Marc McIntosh Date: Mon, 9 Dec 2024 17:28:44 +0100 Subject: [PATCH] fix(history list size): histories larger than 100 where not having old chats removed. --- src/features/History/historySlice.ts | 30 ++++++++++++++++++---------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/src/features/History/historySlice.ts b/src/features/History/historySlice.ts index 9b0e7caa..ba57ba4a 100644 --- a/src/features/History/historySlice.ts +++ b/src/features/History/historySlice.ts @@ -80,18 +80,26 @@ export const historySlice = createSlice({ isTitleGenerated: action.payload.isTitleGenerated, }; - state[chat.id] = chat; - - if (Object.entries(state).length >= 100) { - const sortedByLastUpdated = Object.values(state).sort((a, b) => - b.updatedAt.localeCompare(a.updatedAt), - ); - const newHistory = sortedByLastUpdated.slice(0, 100); - state = newHistory.reduce( - (acc, chat) => ({ ...acc, [chat.id]: chat }), - {}, - ); + const messageMap = { + ...state, + }; + messageMap[chat.id] = chat; + + const messages = Object.values(messageMap); + if (messages.length <= 100) { + return messageMap; } + + const sortedByLastUpdated = messages + .slice(0) + .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + + const newHistory = sortedByLastUpdated.slice(0, 100); + const nextState = newHistory.reduce( + (acc, chat) => ({ ...acc, [chat.id]: chat }), + {}, + ); + return nextState; }, setTitleGenerationCompletionForChat: (