From f2c1e6a915f691b012d0c752e7b8d79dae425893 Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Thu, 12 Nov 2026 00:04:07 +0100 Subject: [PATCH 1/4] fix(chat): keep the reply count of a thread root up to date The "x replies" label of a thread root is read from the cached root message, which only changed when the root message itself was fetched again. The server sends the current reply count of the thread with every message of the thread, over the chat API and the chat relay alike, but it was only stored on the reply itself. Replies fetched by the background prefetch or while the chat was open therefore never reached the label. When messages are stored, copy the reply count of the newest message of each thread onto the cached root message. Every sync path stores messages through upsertChatMessagesAndDeleteTemp, so HTTP polling, signaling and the background prefetch are all covered. Counts that are already stale in the cache are not touched by that, as no new message of the thread may arrive. Opening the main chat therefore also fetches the recently active threads of the conversation and writes their reply counts into the cached roots, the way the web client takes them from its thread list. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- .../talk/chat/data/ChatMessageRepository.kt | 5 + .../network/OfflineFirstChatRepository.kt | 3 + .../talk/chat/viewmodels/ChatViewModel.kt | 26 ++++ .../talk/data/database/dao/ChatMessagesDao.kt | 33 +++++ .../utils/preview/ComposePreviewUtilsDaos.kt | 4 + .../viewmodels/ChatViewModelRoomJoinTest.kt | 46 +++++- .../dao/ChatMessagesDaoThreadRepliesTest.kt | 133 ++++++++++++++++++ 7 files changed, 249 insertions(+), 1 deletion(-) create mode 100644 app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt index 11a2a806c18..ba713159723 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt @@ -134,6 +134,11 @@ interface ChatMessageRepository : LifecycleAwareManager { suspend fun getNumberOfThreadReplies(threadId: Long): Int + /** + * Writes reply counts, keyed by thread id, into the cached root messages of those threads. + */ + suspend fun updateThreadReplies(threadReplies: Map) + @Suppress("LongParameterList") suspend fun sendChatMessage( credentials: String, diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt index 44f16afb2bc..82da6096942 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt @@ -500,6 +500,9 @@ class OfflineFirstChatRepository @Inject constructor( override suspend fun getNumberOfThreadReplies(threadId: Long): Int = chatDao.getNumberOfThreadReplies(internalConversationId, threadId) + override suspend fun updateThreadReplies(threadReplies: Map) = + chatDao.updateThreadRepliesOfThreads(internalConversationId, threadReplies) + override fun getMessage(messageId: Long, bundle: Bundle): Flow = flow { val local = chatDao.getChatMessageEntity(internalConversationId, messageId) diff --git a/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt b/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt index 14773d6d63b..5a6805d544d 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt @@ -1522,10 +1522,35 @@ class ChatViewModel @AssistedInject constructor( ) getCapabilities(user, chatRoomToken, conversation) + refreshThreadReplies(credentials, user) } .launchIn(viewModelScope) } + /** + * Updates the reply counts of the cached thread roots of the main chat with the counts of the recently + * active threads on the server. Does nothing inside a thread or when the server has no threads. + */ + @Suppress("Detekt.TooGenericExceptionCaught") + private fun refreshThreadReplies(credentials: String, user: User) { + if (conversationThreadId != null) return + viewModelScope.launch { + val capabilities = spreedCapabilities.filterNotNull().first() + if (!hasSpreedFeatureCapability(capabilities, SpreedFeatures.THREADS)) return@launch + try { + val url = ApiUtils.getUrlForRecentThreads(version = 1, baseUrl = user.baseUrl, token = chatRoomToken) + val threads = threadsRepository.getThreads(credentials, url, RECENT_THREADS_LIMIT).ocs?.data.orEmpty() + chatRepository.updateThreadReplies( + threads.mapNotNull { it.thread }.associate { it.id.toLong() to it.numReplies } + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.e(TAG, "Failed to refresh the reply counts of the recent threads", e) + } + } + } + fun isChatRelaySupported(user: User): Boolean { val websocketInstance = WebSocketConnectionHelper.getWebSocketInstanceForUser(user) return websocketInstance?.supportsChatRelay() == true @@ -2955,6 +2980,7 @@ class ChatViewModel @AssistedInject constructor( const val HTTP_CODE_OK: Int = 200 private const val CONVERSATION_AND_USER_FLOW_SHARING_TIMEOUT_MS = 5_000L private const val WEBSOCKET_CONNECT_TIMEOUT_MS = 3000L + private const val RECENT_THREADS_LIMIT = 50 private const val WEBSOCKET_POLL_INTERVAL_MS = 50L private const val ROOM_REFRESH_DEBOUNCE_MS = 500L private const val MESSAGES_REBUILD_WINDOW_MS = 200L diff --git a/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt b/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt index e7013721b02..1b51f0319e1 100644 --- a/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt +++ b/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt @@ -99,10 +99,22 @@ interface ChatMessagesDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertChatMessages(chatMessages: List) + /** + * Stores [chatMessages], drops the temporary messages their server copies replace, and carries the + * reply count of every thread in [chatMessages] over to its cached root message. The server sends the + * thread's current count with each message of the thread; the newest one of a thread wins. + */ @Transaction suspend fun upsertChatMessagesAndDeleteTemp(internalConversationId: String, chatMessages: List) { upsertChatMessages(chatMessages) + chatMessages + .filter { it.isThread && it.threadId != null && it.threadReplies != null } + .groupBy { it.threadId!! } + .forEach { (threadId, messages) -> + updateThreadReplies(internalConversationId, threadId, messages.maxBy { it.id }.threadReplies!!) + } + val referenceIds = chatMessages .mapNotNull { it.referenceId } .ifEmpty { return } @@ -113,6 +125,27 @@ interface ChatMessagesDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertChatMessage(chatMessage: ChatMessageEntity) + @Query( + """ + UPDATE ChatMessages + SET threadReplies = :threadReplies + WHERE internalConversationId = :internalConversationId + AND id = :threadId + """ + ) + suspend fun updateThreadReplies(internalConversationId: String, threadId: Long, threadReplies: Int) + + /** + * Writes reply counts, keyed by thread id, into the cached root messages of those threads, all in one + * transaction. + */ + @Transaction + suspend fun updateThreadRepliesOfThreads(internalConversationId: String, threadReplies: Map) { + threadReplies.forEach { (threadId, replies) -> + updateThreadReplies(internalConversationId, threadId, replies) + } + } + @Query( """ SELECT EXISTS( diff --git a/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt b/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt index 40146986ceb..c1c024d2a41 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt @@ -66,6 +66,10 @@ class DummyChatMessagesDaoImpl : ChatMessagesDao { /* */ } + override suspend fun updateThreadReplies(internalConversationId: String, threadId: Long, threadReplies: Int) { + /* */ + } + override suspend fun hasServerCopyOfReferenceId(internalConversationId: String, referenceId: String): Boolean = false diff --git a/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt b/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt index 42058ca8dae..9ff4558e78a 100644 --- a/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt +++ b/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt @@ -32,6 +32,10 @@ import com.nextcloud.talk.models.json.generic.GenericMetaDto import com.nextcloud.talk.models.json.generic.GenericOCS import com.nextcloud.talk.models.json.generic.GenericOverall import com.nextcloud.talk.models.json.participants.ParticipantDto +import com.nextcloud.talk.models.json.threads.ThreadDto +import com.nextcloud.talk.models.json.threads.ThreadInfoDto +import com.nextcloud.talk.models.json.threads.ThreadsOCS +import com.nextcloud.talk.models.json.threads.ThreadsOverall import com.nextcloud.talk.repositories.reactions.ReactionsRepository import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepository import com.nextcloud.talk.threadsoverview.data.ThreadsRepository @@ -65,6 +69,7 @@ import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -100,6 +105,7 @@ class ChatViewModelRoomJoinTest { private lateinit var viewModel: ChatViewModel private lateinit var chatRepository: ChatMessageRepository + private val threadsRepository: ThreadsRepository = mock() private var capabilitiesState: ChatViewModel.ViewState? = null private var initialLoads = 0 private var joins = 0 @@ -136,7 +142,7 @@ class ChatViewModelRoomJoinTest { mock(), network, chatRepository, - mock(), + threadsRepository, conversations, mock(), mock(), @@ -386,6 +392,41 @@ class ChatViewModelRoomJoinTest { assertTrue(capabilitiesState is ChatViewModel.GetCapabilitiesUpdateState) } + @Test + fun `opening the main chat writes the reply counts of the recent threads into the cached thread roots`() { + whenever(network.getCapabilities(any(), any())).thenReturn( + Observable.just(SpreedCapabilityDto(features = listOf("threads"), config = null, version = "")) + ) + wheneverBlocking { threadsRepository.getThreads(any(), any(), any()) }.doReturn( + ThreadsOverall( + ThreadsOCS( + meta = null, + data = listOf( + ThreadInfoDto(thread = ThreadDto(id = THREAD_ID, numReplies = THREAD_REPLIES)) + ) + ) + ) + ) + conversation.value = ConversationResult.Found(conversationModel(5, remoteServer = REMOTE_SERVER)) + + owner.send(Lifecycle.Event.ON_CREATE) + viewModel.initData() + + verifyBlocking(threadsRepository) { getThreads(any(), any(), eq(MAX_RECENT_THREADS)) } + verifyBlocking(chatRepository) { updateThreadReplies(mapOf(THREAD_ID.toLong() to THREAD_REPLIES)) } + } + + @Test + fun `opening the main chat does not ask for threads when the server has none`() { + whenever(network.getCapabilities(any(), any())).thenReturn(Observable.just(SpreedCapabilityDto())) + conversation.value = ConversationResult.Found(conversationModel(5, remoteServer = REMOTE_SERVER)) + + owner.send(Lifecycle.Event.ON_CREATE) + viewModel.initData() + + verifyBlocking(threadsRepository, never()) { getThreads(any(), any(), any()) } + } + private fun conversationModel(lastReadMessage: Int, remoteServer: String = ""): ConversationModel = ConversationModel.mapToConversationModel( ConversationDto( @@ -420,6 +461,9 @@ class ChatViewModelRoomJoinTest { private const val TOKEN = "room-token" private const val HTTP_OK = 200 private const val REMOTE_SERVER = "https://remote.example.com" + private const val THREAD_ID = 100 + private const val THREAD_REPLIES = 23 + private const val MAX_RECENT_THREADS = 50 private val USER = User( id = 1, userId = "me", diff --git a/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt b/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt new file mode 100644 index 00000000000..34a2913dda0 --- /dev/null +++ b/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt @@ -0,0 +1,133 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +package com.nextcloud.talk.data.database.dao + +import android.app.Application +import android.content.Context +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import com.nextcloud.talk.chat.data.model.ChatMessage +import com.nextcloud.talk.data.database.mappers.asEntity +import com.nextcloud.talk.data.database.model.ChatMessageEntity +import com.nextcloud.talk.data.source.local.TalkDatabase +import com.nextcloud.talk.data.user.model.UserEntity +import com.nextcloud.talk.models.json.chat.ChatMessageDto +import com.nextcloud.talk.models.json.conversations.ConversationDto +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The reply count shown on a thread root is taken from the cached root message, while the server sends the + * thread's current count with every message of the thread. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class, sdk = [33]) +class ChatMessagesDaoThreadRepliesTest { + + private lateinit var db: TalkDatabase + + @Before + fun setUp() { + val context = ApplicationProvider.getApplicationContext() + db = Room.inMemoryDatabaseBuilder(context, TalkDatabase::class.java).build() + runBlocking { + db.usersDao().saveUser(UserEntity(id = ACCOUNT_ID, userId = "me", username = "me", baseUrl = BASE_URL)) + db.conversationsDao().upsertConversations( + ACCOUNT_ID, + listOf(ConversationDto(token = ROOM_TOKEN).asEntity(ACCOUNT_ID)) + ) + } + } + + @After + fun tearDown() { + db.close() + } + + @Test + fun `a new reply updates the reply count of the cached thread root`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + + store(threadMessage(id = ROOT_ID + 2, threadReplies = 2)) + + assertEquals(2, threadRepliesOfRoot()) + } + + @Test + fun `the newest message of a thread decides the reply count`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + + store( + threadMessage(id = ROOT_ID + 3, threadReplies = 3), + threadMessage(id = ROOT_ID + 2, threadReplies = 2) + ) + + assertEquals(3, threadRepliesOfRoot()) + } + + @Test + fun `a message outside of a thread leaves the reply count alone`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + + store(threadMessage(id = ROOT_ID + 2, threadReplies = 0).copy(isThread = false, threadId = ROOT_ID + 2)) + + assertEquals(1, threadRepliesOfRoot()) + } + + @Test + fun `the reply counts of several threads are written into their cached roots`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + + db.chatMessagesDao().updateThreadRepliesOfThreads( + INTERNAL_CONVERSATION_ID, + mapOf(ROOT_ID to 23, ROOT_ID + 1000 to 5) + ) + + assertEquals(23, threadRepliesOfRoot()) + } + + private suspend fun store(vararg messages: ChatMessageEntity) { + db.chatMessagesDao().upsertChatMessagesAndDeleteTemp(INTERNAL_CONVERSATION_ID, messages.toList()) + } + + private suspend fun threadRepliesOfRoot(): Int? = + db.chatMessagesDao().getChatMessageEntity(INTERNAL_CONVERSATION_ID, ROOT_ID)?.threadReplies + + private fun threadMessage(id: Long, threadReplies: Int) = + ChatMessageDto( + id = id, + token = ROOM_TOKEN, + actorType = "users", + actorId = "other", + actorDisplayName = "Other", + message = "message $id", + messageType = "comment", + systemMessageType = ChatMessage.SystemMessageType.DUMMY, + threadId = ROOT_ID, + hasThread = true, + threadReplies = threadReplies + ).asEntity(ACCOUNT_ID) + + companion object { + private const val ACCOUNT_ID = 1L + private const val ROOM_TOKEN = "room1" + private const val INTERNAL_CONVERSATION_ID = "$ACCOUNT_ID@$ROOM_TOKEN" + private const val BASE_URL = "https://server.example.com" + private const val ROOT_ID = 100L + } +} From f4eed978cf69fe309d6c467cb873bdd03ac920a5 Mon Sep 17 00:00:00 2001 From: Andy Scherzinger Date: Fri, 13 Nov 2026 09:45:00 +0100 Subject: [PATCH 2/4] refactor(chat): remove the unused local thread reply counting The reply count of a thread is taken from the server, so the local count of replies by parent message is no longer used anywhere. Remove the query and its repository and preview wrappers. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Andy Scherzinger --- .../talk/chat/data/ChatMessageRepository.kt | 2 -- .../data/network/OfflineFirstChatRepository.kt | 3 --- .../talk/data/database/dao/ChatMessagesDao.kt | 14 -------------- .../talk/utils/preview/ComposePreviewUtilsDaos.kt | 2 -- 4 files changed, 21 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt index ba713159723..9c66b5a9148 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt @@ -132,8 +132,6 @@ interface ChatMessageRepository : LifecycleAwareManager { fun observeParentMessages(parentIds: List): Flow> - suspend fun getNumberOfThreadReplies(threadId: Long): Int - /** * Writes reply counts, keyed by thread id, into the cached root messages of those threads. */ diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt index 82da6096942..071c0050215 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt @@ -497,9 +497,6 @@ class OfflineFirstChatRepository @Inject constructor( lastCommonRead = newXChatLastCommonRead ) - override suspend fun getNumberOfThreadReplies(threadId: Long): Int = - chatDao.getNumberOfThreadReplies(internalConversationId, threadId) - override suspend fun updateThreadReplies(threadReplies: Map) = chatDao.updateThreadRepliesOfThreads(internalConversationId, threadReplies) diff --git a/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt b/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt index 1b51f0319e1..2ec8b9a6638 100644 --- a/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt +++ b/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt @@ -506,18 +506,4 @@ interface ChatMessagesDao { """ ) fun deleteMessagesOlderThan(internalConversationId: String, messageId: Long) - - @Query( - """ - SELECT COUNT(*) - FROM ChatMessages AS child - INNER JOIN ChatMessages AS parent - ON child.parent = parent.id - WHERE child.internalConversationId = :internalConversationId - AND child.isTemporary = 0 - AND child.messageType = 'comment' - AND parent.threadId = :threadId - """ - ) - fun getNumberOfThreadReplies(internalConversationId: String, threadId: Long): Int } diff --git a/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt b/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt index c1c024d2a41..1c134862069 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt @@ -181,8 +181,6 @@ class DummyChatMessagesDaoImpl : ChatMessagesDao { oldestMessageId: Long, newestMessageId: Long ): Long? = null - - override fun getNumberOfThreadReplies(internalConversationId: String, threadId: Long): Int = 0 } class DummyUserDaoImpl : UsersDao { From 1b6be13cb40106b5ea774ecf6ebccc30c7b0fd44 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Tue, 17 Nov 2026 14:46:58 +0100 Subject: [PATCH 3/4] fix(chat): keep the reply count of an open thread up to date Inside a thread, the "x replies" subtitle of the toolbar was taken from the thread endpoint, which is only asked once when the thread is opened. Replies that arrived while the thread was open never reached it. The cached root message of the thread already follows the chat, as every stored thread message carries the thread's current reply count over to it. Observe that root and show its count in the toolbar. The higher of the root's count and the endpoint's count is shown, as a thread's reply count only grows and the root may not be cached yet. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../com/nextcloud/talk/chat/ChatActivity.kt | 14 ++++- .../talk/chat/data/ChatMessageRepository.kt | 5 ++ .../network/OfflineFirstChatRepository.kt | 5 ++ .../talk/chat/viewmodels/ChatViewModel.kt | 17 +++++ .../viewmodels/ChatViewModelRoomJoinTest.kt | 62 ++++++++++++++----- 5 files changed, 85 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt index 7759878be85..17661a54694 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt @@ -394,6 +394,9 @@ class ChatActivity : var openedViaNotification: Boolean = false var conversationThreadInfo: ThreadInfoDto? = null + + // Reply count of the open thread from its cached root message, which follows the chat while it is open + private var threadRootReplies: Int? = null val conversationUser: User get() = chatViewModel.currentUser lateinit var spreedCapabilities: SpreedCapabilityDto @@ -1858,6 +1861,13 @@ class ChatActivity : } } } + + this.lifecycleScope.launch { + chatViewModel.threadRootReplies.collect { replies -> + threadRootReplies = replies + updateToolbarState() + } + } } private fun removeUnreadMessagesMarker() { @@ -2177,7 +2187,9 @@ class ChatActivity : private fun buildToolbarSubtitle(conversation: ConversationModel?): String = when { isChatThread() -> { - val count = conversationThreadInfo?.thread?.numReplies ?: 0 + // The thread endpoint is only asked once when the thread is opened, while the cached root follows + // the chat. A thread's reply count only grows, so the higher of both is the current one. + val count = maxOf(conversationThreadInfo?.thread?.numReplies ?: 0, threadRootReplies ?: 0) resources.getQuantityString(R.plurals.thread_replies, count, count) } conversation?.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL -> { diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt index 9c66b5a9148..80b099605ed 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt @@ -137,6 +137,11 @@ interface ChatMessageRepository : LifecycleAwareManager { */ suspend fun updateThreadReplies(threadReplies: Map) + /** + * Emits the reply count stored on the cached root message of [threadId], or null while the root is not cached. + */ + fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow + @Suppress("LongParameterList") suspend fun sendChatMessage( credentials: String, diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt index 071c0050215..37b1be7c8a6 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt @@ -500,6 +500,11 @@ class OfflineFirstChatRepository @Inject constructor( override suspend fun updateThreadReplies(threadReplies: Map) = chatDao.updateThreadRepliesOfThreads(internalConversationId, threadReplies) + override fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow = + chatDao.observeMessage(internalConversationId, threadId) + .map { it?.threadReplies } + .distinctUntilChanged() + override fun getMessage(messageId: Long, bundle: Bundle): Flow = flow { val local = chatDao.getChatMessageEntity(internalConversationId, messageId) diff --git a/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt b/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt index 5a6805d544d..67b2f97a91d 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt @@ -121,6 +121,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChangedBy +import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first @@ -840,6 +841,22 @@ class ChatViewModel @AssistedInject constructor( } } + /** + * Reply count of the open thread, read from its cached root message. Every thread message that is stored + * carries the thread's current count over to the root, so this follows the chat while it is open. Emits + * nothing outside of a thread. + */ + @OptIn(ExperimentalCoroutinesApi::class) + val threadRootReplies: Flow = + conversationThreadId?.let { threadId -> + conversationAndUserFlow + .flatMapLatest { (conversation, _) -> + chatRepository.observeThreadReplies(conversation.internalId, threadId) + } + .filterNotNull() + .distinctUntilChanged() + } ?: emptyFlow() + // ------------------------------ // Last read message cache // ------------------------------ diff --git a/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt b/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt index 9ff4558e78a..b405774ffed 100644 --- a/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt +++ b/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt @@ -54,6 +54,10 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @@ -105,6 +109,7 @@ class ChatViewModelRoomJoinTest { private lateinit var viewModel: ChatViewModel private lateinit var chatRepository: ChatMessageRepository + private lateinit var createViewModel: (threadId: Long?) -> ChatViewModel private val threadsRepository: ThreadsRepository = mock() private var capabilitiesState: ChatViewModel.ViewState? = null private var initialLoads = 0 @@ -136,24 +141,27 @@ class ChatViewModelRoomJoinTest { GenericOverall(GenericOCS(GenericMetaDto(statusCode = HTTP_OK))) } chatRepository = mockWithEmptyFlows() + createViewModel = { threadId -> + ChatViewModel( + mock(), + mock(), + network, + chatRepository, + threadsRepository, + conversations, + mock(), + mock(), + mock(), + mock(), + userManager, + appScope, + USER, + TOKEN, + threadId + ) + } - val newViewModel = ChatViewModel( - mock(), - mock(), - network, - chatRepository, - threadsRepository, - conversations, - mock(), - mock(), - mock(), - mock(), - userManager, - appScope, - USER, - TOKEN, - null - ) + val newViewModel = createViewModel(null) viewModel = ViewModelProvider( viewModelStore, object : ViewModelProvider.Factory { @@ -427,6 +435,26 @@ class ChatViewModelRoomJoinTest { verifyBlocking(threadsRepository, never()) { getThreads(any(), any(), any()) } } + @Test + fun `inside a thread the reply count follows the cached thread root`() = + runBlocking { + whenever(chatRepository.observeThreadReplies(any(), eq(THREAD_ID.toLong()))) + .thenReturn(flowOf(null, 3, 3, THREAD_REPLIES)) + owner.send(Lifecycle.Event.ON_CREATE) + + val replies = createViewModel(THREAD_ID.toLong()).threadRootReplies.take(2).toList() + + assertEquals(listOf(3, THREAD_REPLIES), replies) + } + + @Test + fun `the main chat has no thread reply count`() = + runBlocking { + owner.send(Lifecycle.Event.ON_CREATE) + + assertEquals(emptyList(), viewModel.threadRootReplies.toList()) + } + private fun conversationModel(lastReadMessage: Int, remoteServer: String = ""): ConversationModel = ConversationModel.mapToConversationModel( ConversationDto( From a07f7635b1d3ce6fbe4d4aed81ec2079887b903f Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Tue, 17 Nov 2026 15:32:56 +0100 Subject: [PATCH 4/4] fix(chat): never lower a thread's reply count with a stale one Each stored batch of messages wrote the count of its newest thread message onto the thread root, so a response that took longer than a relayed reply could lower the count again until the next reply. A thread's reply count only grows on the server, so only raise the stored count, and write all counts through one path. Inside a thread, the reply count in the toolbar was read from the cached root message only, so it did not follow the chat when the root was not cached, e.g. for a thread opened from a notification whose root is older than the loaded messages. Read the highest count of all cached messages of the thread instead, as every message of a thread carries the thread's count. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../com/nextcloud/talk/chat/ChatActivity.kt | 14 +++---- .../talk/chat/data/ChatMessageRepository.kt | 2 +- .../network/OfflineFirstChatRepository.kt | 3 +- .../talk/chat/viewmodels/ChatViewModel.kt | 7 ++-- .../talk/data/database/dao/ChatMessagesDao.kt | 42 ++++++++++++++----- .../utils/preview/ComposePreviewUtilsDaos.kt | 2 + .../viewmodels/ChatViewModelRoomJoinTest.kt | 6 +-- .../dao/ChatMessagesDaoThreadRepliesTest.kt | 26 +++++++++++- 8 files changed, 74 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt index 17661a54694..731b452a110 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt @@ -395,8 +395,8 @@ class ChatActivity : var openedViaNotification: Boolean = false var conversationThreadInfo: ThreadInfoDto? = null - // Reply count of the open thread from its cached root message, which follows the chat while it is open - private var threadRootReplies: Int? = null + // Reply count of the open thread from its cached messages, which follows the chat while it is open + private var cachedThreadReplies: Int? = null val conversationUser: User get() = chatViewModel.currentUser lateinit var spreedCapabilities: SpreedCapabilityDto @@ -1863,8 +1863,8 @@ class ChatActivity : } this.lifecycleScope.launch { - chatViewModel.threadRootReplies.collect { replies -> - threadRootReplies = replies + chatViewModel.cachedThreadReplies.collect { replies -> + cachedThreadReplies = replies updateToolbarState() } } @@ -2187,9 +2187,9 @@ class ChatActivity : private fun buildToolbarSubtitle(conversation: ConversationModel?): String = when { isChatThread() -> { - // The thread endpoint is only asked once when the thread is opened, while the cached root follows - // the chat. A thread's reply count only grows, so the higher of both is the current one. - val count = maxOf(conversationThreadInfo?.thread?.numReplies ?: 0, threadRootReplies ?: 0) + // The thread endpoint is only asked once when the thread is opened, while the cached messages + // follow the chat. A thread's reply count only grows, so the higher of both is the current one. + val count = maxOf(conversationThreadInfo?.thread?.numReplies ?: 0, cachedThreadReplies ?: 0) resources.getQuantityString(R.plurals.thread_replies, count, count) } conversation?.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL -> { diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt index 80b099605ed..d7cbc5f598c 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/ChatMessageRepository.kt @@ -138,7 +138,7 @@ interface ChatMessageRepository : LifecycleAwareManager { suspend fun updateThreadReplies(threadReplies: Map) /** - * Emits the reply count stored on the cached root message of [threadId], or null while the root is not cached. + * Emits the highest reply count stored on the cached messages of [threadId], or null while none is cached. */ fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow diff --git a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt index 37b1be7c8a6..10c8111aeee 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/data/network/OfflineFirstChatRepository.kt @@ -501,8 +501,7 @@ class OfflineFirstChatRepository @Inject constructor( chatDao.updateThreadRepliesOfThreads(internalConversationId, threadReplies) override fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow = - chatDao.observeMessage(internalConversationId, threadId) - .map { it?.threadReplies } + chatDao.observeThreadReplies(internalConversationId, threadId) .distinctUntilChanged() override fun getMessage(messageId: Long, bundle: Bundle): Flow = diff --git a/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt b/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt index 67b2f97a91d..8dbda049dfa 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/viewmodels/ChatViewModel.kt @@ -842,12 +842,11 @@ class ChatViewModel @AssistedInject constructor( } /** - * Reply count of the open thread, read from its cached root message. Every thread message that is stored - * carries the thread's current count over to the root, so this follows the chat while it is open. Emits - * nothing outside of a thread. + * Reply count of the open thread, read from its cached messages. Every thread message carries the thread's + * current count, so this follows the chat while it is open. Emits nothing outside of a thread. */ @OptIn(ExperimentalCoroutinesApi::class) - val threadRootReplies: Flow = + val cachedThreadReplies: Flow = conversationThreadId?.let { threadId -> conversationAndUserFlow .flatMapLatest { (conversation, _) -> diff --git a/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt b/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt index 2ec8b9a6638..5c61fc7a475 100644 --- a/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt +++ b/app/src/main/java/com/nextcloud/talk/data/database/dao/ChatMessagesDao.kt @@ -102,18 +102,19 @@ interface ChatMessagesDao { /** * Stores [chatMessages], drops the temporary messages their server copies replace, and carries the * reply count of every thread in [chatMessages] over to its cached root message. The server sends the - * thread's current count with each message of the thread; the newest one of a thread wins. + * thread's current count with each message of the thread. */ @Transaction suspend fun upsertChatMessagesAndDeleteTemp(internalConversationId: String, chatMessages: List) { upsertChatMessages(chatMessages) - chatMessages - .filter { it.isThread && it.threadId != null && it.threadReplies != null } - .groupBy { it.threadId!! } - .forEach { (threadId, messages) -> - updateThreadReplies(internalConversationId, threadId, messages.maxBy { it.id }.threadReplies!!) - } + updateThreadRepliesOfThreads( + internalConversationId, + chatMessages + .filter { it.isThread && it.threadId != null && it.threadReplies != null } + .groupBy { it.threadId!! } + .mapValues { (_, messages) -> messages.maxOf { it.threadReplies!! } } + ) val referenceIds = chatMessages .mapNotNull { it.referenceId } @@ -125,10 +126,15 @@ interface ChatMessagesDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertChatMessage(chatMessage: ChatMessageEntity) + /** + * Raises the reply count of the cached root message of [threadId] to [threadReplies]. A thread's reply count + * only grows on the server, so a lower count is a stale one, e.g. from a response that took longer than a + * relayed reply, and is ignored. + */ @Query( """ UPDATE ChatMessages - SET threadReplies = :threadReplies + SET threadReplies = MAX(COALESCE(threadReplies, 0), :threadReplies) WHERE internalConversationId = :internalConversationId AND id = :threadId """ @@ -136,8 +142,24 @@ interface ChatMessagesDao { suspend fun updateThreadReplies(internalConversationId: String, threadId: Long, threadReplies: Int) /** - * Writes reply counts, keyed by thread id, into the cached root messages of those threads, all in one - * transaction. + * Emits the highest reply count stored on the cached messages of [threadId], or null while none is cached. + * Every message of a thread carries the thread's count, so this follows the thread even when its root + * message is not cached. + */ + @Query( + """ + SELECT MAX(threadReplies) + FROM ChatMessages + WHERE internalConversationId = :internalConversationId + AND threadId = :threadId + AND isThread = 1 + """ + ) + fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow + + /** + * Raises reply counts, keyed by thread id, on the cached root messages of those threads, all in one + * transaction, see [updateThreadReplies]. */ @Transaction suspend fun updateThreadRepliesOfThreads(internalConversationId: String, threadReplies: Map) { diff --git a/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt b/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt index 1c134862069..0edd89a9af3 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/preview/ComposePreviewUtilsDaos.kt @@ -70,6 +70,8 @@ class DummyChatMessagesDaoImpl : ChatMessagesDao { /* */ } + override fun observeThreadReplies(internalConversationId: String, threadId: Long): Flow = flowOf() + override suspend fun hasServerCopyOfReferenceId(internalConversationId: String, referenceId: String): Boolean = false diff --git a/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt b/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt index b405774ffed..4229fa29a7f 100644 --- a/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt +++ b/app/src/test/java/com/nextcloud/talk/chat/viewmodels/ChatViewModelRoomJoinTest.kt @@ -436,13 +436,13 @@ class ChatViewModelRoomJoinTest { } @Test - fun `inside a thread the reply count follows the cached thread root`() = + fun `inside a thread the reply count follows the cached thread messages`() = runBlocking { whenever(chatRepository.observeThreadReplies(any(), eq(THREAD_ID.toLong()))) .thenReturn(flowOf(null, 3, 3, THREAD_REPLIES)) owner.send(Lifecycle.Event.ON_CREATE) - val replies = createViewModel(THREAD_ID.toLong()).threadRootReplies.take(2).toList() + val replies = createViewModel(THREAD_ID.toLong()).cachedThreadReplies.take(2).toList() assertEquals(listOf(3, THREAD_REPLIES), replies) } @@ -452,7 +452,7 @@ class ChatViewModelRoomJoinTest { runBlocking { owner.send(Lifecycle.Event.ON_CREATE) - assertEquals(emptyList(), viewModel.threadRootReplies.toList()) + assertEquals(emptyList(), viewModel.cachedThreadReplies.toList()) } private fun conversationModel(lastReadMessage: Int, remoteServer: String = ""): ConversationModel = diff --git a/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt b/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt index 34a2913dda0..eb5748138a6 100644 --- a/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt +++ b/app/src/test/java/com/nextcloud/talk/data/database/dao/ChatMessagesDaoThreadRepliesTest.kt @@ -18,6 +18,7 @@ import com.nextcloud.talk.data.source.local.TalkDatabase import com.nextcloud.talk.data.user.model.UserEntity import com.nextcloud.talk.models.json.chat.ChatMessageDto import com.nextcloud.talk.models.json.conversations.ConversationDto +import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals @@ -66,7 +67,7 @@ class ChatMessagesDaoThreadRepliesTest { } @Test - fun `the newest message of a thread decides the reply count`() = + fun `the highest count of a thread decides the reply count`() = runBlocking { store(threadMessage(id = ROOT_ID, threadReplies = 1)) @@ -78,6 +79,29 @@ class ChatMessagesDaoThreadRepliesTest { assertEquals(3, threadRepliesOfRoot()) } + @Test + fun `a stale count stored later does not lower the reply count`() = + runBlocking { + store(threadMessage(id = ROOT_ID, threadReplies = 1)) + store(threadMessage(id = ROOT_ID + 3, threadReplies = 3)) + + store(threadMessage(id = ROOT_ID + 2, threadReplies = 2)) + + assertEquals(3, threadRepliesOfRoot()) + } + + @Test + fun `the reply count of a thread follows its messages when the root is not cached`() = + runBlocking { + store(threadMessage(id = ROOT_ID + 2, threadReplies = 2)) + store(threadMessage(id = ROOT_ID + 3, threadReplies = 3)) + + assertEquals( + 3, + db.chatMessagesDao().observeThreadReplies(INTERNAL_CONVERSATION_ID, ROOT_ID).first() + ) + } + @Test fun `a message outside of a thread leaves the reply count alone`() = runBlocking {