From 82fb263438f77745e3d958c78502df202cb9fffb Mon Sep 17 00:00:00 2001 From: JC Brand Date: Mon, 14 Mar 2022 21:19:43 +0100 Subject: [PATCH] Explicitly sort messages before pruning to avoid a race-condition where messages aren't sorted and the wrong message gets pruned. --- src/headless/plugins/chat/model.js | 4 ++-- src/headless/shared/chat/utils.js | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/headless/plugins/chat/model.js b/src/headless/plugins/chat/model.js index 3639b05ab..b96720603 100644 --- a/src/headless/plugins/chat/model.js +++ b/src/headless/plugins/chat/model.js @@ -6,7 +6,7 @@ import log from '@converse/headless/log'; import pick from "lodash-es/pick"; import { Model } from '@converse/skeletor/src/model.js'; import { _converse, api, converse } from "../../core.js"; -import { debouncedPruneHistory, pruneHistory } from '@converse/headless/shared/chat/utils.js'; +import { debouncedPruneHistory } from '@converse/headless/shared/chat/utils.js'; import { getMediaURLsMetadata } from '@converse/headless/shared/parsers.js'; import { getOpenPromise } from '@converse/openpromise'; import { initStorage } from '@converse/headless/utils/storage.js'; @@ -350,7 +350,7 @@ const ChatBox = ModelWithContact.extend({ api.settings.get('pruning_behavior') === 'unscrolled' && !this.ui.get('scrolled') ) { - pruneHistory(this); + debouncedPruneHistory(this); } }, diff --git a/src/headless/shared/chat/utils.js b/src/headless/shared/chat/utils.js index 7494d12ea..a56de8fed 100644 --- a/src/headless/shared/chat/utils.js +++ b/src/headless/shared/chat/utils.js @@ -7,6 +7,9 @@ export function pruneHistory (model) { const max_history = api.settings.get('prune_messages_above'); if (max_history && typeof max_history === 'number') { if (model.messages.length > max_history) { + + model.messages.sort(); // Explicitly call sort() to avoid race-conditions + const non_empty_messages = model.messages.filter((m) => !u.isEmptyMessage(m)); if (non_empty_messages.length > max_history) { while (non_empty_messages.length > max_history) { @@ -58,4 +61,4 @@ export function getMediaURLs (arr, text, offset=0) { }).filter(o => o); } -export const debouncedPruneHistory = debounce(pruneHistory, 250); +export const debouncedPruneHistory = debounce(pruneHistory, 500);