From a0dce1d4c6f81ef60abe3584ac9fd87c19077f71 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Wed, 18 Nov 2026 17:37:48 +0100 Subject: [PATCH 1/5] fix(chat): keep the conversation's place when a message arrives while reading older ones Follow a new message only on the first load, for the user's own message, or while the previous newest one's bottom edge is on screen. Otherwise keep the place and show a "New message" hint that scrolls down when tapped. --- .../polybazaar/chat/ui/ConversationScreen.kt | 106 +++++++++++++++--- app/src/main/res/values/strings.xml | 1 + 2 files changed, 89 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt index 1bbdd0e2..419fddc7 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt @@ -1,6 +1,7 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.ui +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement @@ -23,15 +24,22 @@ import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.SolidColor @@ -71,6 +79,7 @@ import java.time.ZoneId import java.time.ZoneOffset import java.time.format.DateTimeFormatter import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch object ConversationScreenTags { const val SCREEN = "conversation_screen" @@ -88,6 +97,7 @@ object ConversationScreenTags { const val SEND_BUTTON = "conversation_send_button" const val SEND_ERROR = "conversation_send_error" const val LENGTH_COUNTER = "conversation_length_counter" + const val NEW_MESSAGE_HINT = "conversation_new_message_hint" /** Tag of the bubble of the signed-in user's message with [id]. */ fun myMessage(id: String) = "conversation_my_message_$id" @@ -408,37 +418,97 @@ private fun EmptyState( } /** - * The messages, oldest at the top, with the load error and Retry above them when a reload failed. + * The messages, oldest at the top, with the load error and Retry above them when a reload failed, + * and a hint over the bottom while a message has arrived below the view. */ @Composable private fun MessageList(uiState: ConversationUiState, zone: ZoneId, onRetry: () -> Unit) { val messages = uiState.messages + val newest = messages.lastOrNull() val listState = rememberLazyListState() - // The list keeps its place by key, so a new message would arrive below the view without this. - LaunchedEffect(messages.lastOrNull()?.id) { listState.scrollToItem(0) } + val scope = rememberCoroutineScope() + // The newest message already followed or hinted at, and whether one is waiting below the view. + // Saved across recreation, as the list's position is. + var previousNewestId by rememberSaveable { mutableStateOf(null) } + var newestUnseen by rememberSaveable { mutableStateOf(false) } + // The list keeps its place by key, so a new message arrives below the view unless this follows + // it. One from the other participant is followed only when the previous newest's bottom edge is + // on screen: then the user is reading the end of the conversation. Looked up by key, it is found + // whether or not the new one is laid out yet. + // requestScrollToItem takes no scroll lock, so a finger on the list cannot cancel the follow. + LaunchedEffect(newest?.id) { + val previous = previousNewestId + if (newest == null || newest.id == previous) return@LaunchedEffect + val layout = listState.layoutInfo + val follow = + previous == null || + newest.senderUid == uiState.myUid || + layout.visibleItemsInfo.any { + it.key == previous && it.offset >= layout.viewportStartOffset + } + previousNewestId = newest.id + if (follow) listState.requestScrollToItem(0) else newestUnseen = true + } + // In the reversed list the newest message is item 0, first from the bottom. The hint goes only + // once that is in view, so a tap whose scroll is cut short leaves it up. + LaunchedEffect(listState) { + snapshotFlow { newestUnseen && listState.firstVisibleItemIndex == 0 } + .collect { seen -> if (seen) newestUnseen = false } + } Column(modifier = Modifier.fillMaxSize()) { uiState.loadError?.let { LoadErrorRow(text = it.message(), onRetry = onRetry) } - // Laid out from the bottom, newest first, so the newest message stays in view, footer - // included, however long it is and whatever shrinks the list. - LazyColumn( - state = listState, - modifier = Modifier.weight(1f).fillMaxWidth().testTag(ConversationScreenTags.MESSAGE_LIST), - contentPadding = PaddingValues(horizontal = PageMargin, vertical = 12.dp), - reverseLayout = true, - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - items(messages.asReversed(), key = { it.id }) { message -> - MessageBubble( - message = message, - isMine = message.senderUid == uiState.myUid, - otherUsername = uiState.otherUser?.username, - zone = zone, + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + // Laid out from the bottom, newest first, so the newest message stays in view, footer + // included, however long it is and whatever shrinks the list. + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize().testTag(ConversationScreenTags.MESSAGE_LIST), + contentPadding = PaddingValues(horizontal = PageMargin, vertical = 12.dp), + reverseLayout = true, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + items(messages.asReversed(), key = { it.id }) { message -> + MessageBubble( + message = message, + isMine = message.senderUid == uiState.myUid, + otherUsername = uiState.otherUser?.username, + zone = zone, + ) + } + } + if (newestUnseen) { + NewMessageHint( + onClick = { scope.launch { listState.animateScrollToItem(0) } }, + modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp), ) } } } } +/** Says a message arrived below the view; tapping it scrolls down to the newest message. */ +@Composable +private fun NewMessageHint(onClick: () -> Unit, modifier: Modifier = Modifier) { + OutlinedButton( + onClick = onClick, + modifier = + modifier + // Announced when it appears: TalkBack's focus is on the older message being read. + .semantics { liveRegion = LiveRegionMode.Polite } + .testTag(ConversationScreenTags.NEW_MESSAGE_HINT), + shape = RoundedCornerShape(20.dp), + border = BorderStroke(1.dp, AuthColors.Outline), + colors = ButtonDefaults.outlinedButtonColors(containerColor = AuthColors.CardBackground), + ) { + Text( + text = stringResource(R.string.conversation_new_message), + color = AuthColors.Accent, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + ) + } +} + /** A reload error above messages that stay shown, with Retry as a text button. */ @Composable private fun LoadErrorRow(text: String, onRetry: () -> Unit) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ac2de988..3cf60d7a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -92,6 +92,7 @@ Write a message… Conversation closed Send + New message %1$d/%2$d Message too long: at most %d character From 4121ba31c43bfbc493eb9738c3742c3661a514cf Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Wed, 18 Nov 2026 17:37:48 +0100 Subject: [PATCH 2/5] test(chat): cover following, keeping the place and the new-message hint --- .../chat/ui/ConversationScreenTest.kt | 180 +++++++++++++++++- 1 file changed, 172 insertions(+), 8 deletions(-) diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt index e2a27c36..dd4b7cef 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt @@ -2,10 +2,12 @@ package com.android.polybazaar.chat.ui import android.content.Context +import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher @@ -13,6 +15,7 @@ import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertContentDescriptionEquals import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertHasClickAction import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotDisplayed @@ -22,6 +25,7 @@ import androidx.compose.ui.test.assertWidthIsEqualTo import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasTestTag +import androidx.compose.ui.test.junit4.StateRestorationTester import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText @@ -29,6 +33,8 @@ import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollToIndex import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performTextReplacement +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipe import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle @@ -161,6 +167,38 @@ class ConversationScreenTest { ) } + /** When [manyMessages] were sent. */ + private val manyStart = Instant.parse("2026-11-11T08:00:00Z") + + /** More messages than fit on the screen, oldest first: the renter's are the even ones. */ + private val manyMessages = + List(50) { + ChatMessage("m$it", if (it % 2 == 0) "renter" else james.uid, "Message $it", manyStart) + } + + /** + * Shows [messages], through [restoration] when given, and returns how to make a new one arrive + * after them. + */ + private fun showManyMessages( + messages: List = manyMessages, + restoration: StateRestorationTester? = null, + ): (ChatMessage) -> Unit { + var uiState by mutableStateOf(loaded.copy(messages = messages)) + val content: @Composable () -> Unit = { + ConversationContent(uiState = uiState, zone = ZoneOffset.UTC) + } + if (restoration != null) restoration.setContent(content) + else composeTestRule.setContent(content) + return { message -> uiState = uiState.copy(messages = uiState.messages + message) } + } + + /** Scrolls up to the oldest of [manyMessages], the last item of the list. */ + private fun scrollToTheOldest() { + node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(manyMessages.lastIndex) + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + } + /** Every text of the empty state. */ private fun emptyStateTexts() = composeTestRule.onAllNodes( @@ -399,18 +437,12 @@ class ConversationScreenTest { @Test fun manyMessages_openOnTheLatest_andFollowANewOne() { - val start = Instant.parse("2026-11-11T08:00:00Z") - val many = - List(50) { - ChatMessage("m$it", if (it % 2 == 0) "renter" else james.uid, "Message $it", start) - } - var uiState by mutableStateOf(loaded.copy(messages = many)) - composeTestRule.setContent { ConversationContent(uiState = uiState, zone = ZoneOffset.UTC) } + val arrive = showManyMessages() assertFullyInTheList(node(ConversationScreenTags.theirMessage("m49"))) node(ConversationScreenTags.myMessage("m0")).assertIsNotDisplayed() - uiState = uiState.copy(messages = many + ChatMessage("m50", "renter", "On my way", start)) + arrive(ChatMessage("m50", "renter", "On my way", manyStart)) assertFullyInTheList(node(ConversationScreenTags.myMessage("m50"))) // The oldest message was only out of view: the list holds it last, newest first. @@ -418,6 +450,138 @@ class ConversationScreenTest { node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() } + @Test + fun theirNewMessageWhileTheLatestIsInView_isFollowed_withoutTheHint() { + val arrive = showManyMessages() + + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + + assertFullyInTheList(node(ConversationScreenTags.theirMessage("m50"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun theirNewMessagesWhileReadingOlderOnes_keepThePlace_andShowTheHint() { + val arrive = showManyMessages() + scrollToTheOldest() + + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + composeTestRule.waitForIdle() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + arrive(ChatMessage("m51", james.uid, "At ten", manyStart)) + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.theirMessage("m50")).assertIsNotDisplayed() + node(ConversationScreenTags.theirMessage("m51")).assertIsNotDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT) + .assertIsDisplayed() + .assertTextEquals(string(R.string.conversation_new_message)) + .assertHasClickAction() + .assert(isPoliteLiveRegion()) + } + + @Test + fun theirNewMessageDuringADragAtTheLatest_isFollowedOnceTheFingerLifts() { + val arrive = showManyMessages() + // Past the touch slop, so the finger holds the list's scroll while it stays down. + node(ConversationScreenTags.MESSAGE_LIST).performTouchInput { + down(center) + moveBy(Offset(0f, viewConfiguration.touchSlop + 5f)) + moveBy(Offset(0f, 5f)) + } + node(ConversationScreenTags.theirMessage("m49")).assertIsDisplayed() + + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + composeTestRule.waitForIdle() + // Held still before lifting, so the list does not fling. + composeTestRule.mainClock.advanceTimeBy(500) + node(ConversationScreenTags.MESSAGE_LIST).performTouchInput { up() } + + assertFullyInTheList(node(ConversationScreenTags.theirMessage("m50"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + // Real text heights, and a window shorter than the long message, so its start and its end are + // not in view together. + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) + @Config(qualifiers = "w360dp-h480dp") + fun theirNewMessageWhileReadingTheStartOfALongNewestOne_keepsThePlace_andShowsTheHint() { + // The longest message the rules allow. + val long = + ChatMessage( + "m49", + james.uid, + "word ".repeat(ChatRules.MAX_MESSAGE_LENGTH / "word ".length), + manyStart, + ) + val arrive = showManyMessages(manyMessages.dropLast(1) + long) + node(ConversationScreenTags.MESSAGE_LIST).performTouchInput { + swipe(Offset(centerX, top + 20f), Offset(centerX, top + 220f), durationMillis = 2000) + } + val list = node(ConversationScreenTags.MESSAGE_LIST).fetchSemanticsNode().boundsInRoot + val reading = node(ConversationScreenTags.theirMessage("m49")).fetchSemanticsNode() + val readingTop = reading.positionInRoot.y + assertTrue("Its end is in view", readingTop + reading.size.height > list.bottom) + + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + + val after = node(ConversationScreenTags.theirMessage("m49")).fetchSemanticsNode() + assertEquals(readingTop, after.positionInRoot.y, 0.5f) + node(ConversationScreenTags.theirMessage("m50")).assertIsNotDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + } + + @Test + fun recreatedWhileTheHintShows_keepsTheHintAndThePlace() { + val restoration = StateRestorationTester(composeTestRule) + val arrive = showManyMessages(restoration = restoration) + scrollToTheOldest() + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + + restoration.emulateSavedInstanceStateRestore() + + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + } + + @Test + fun tappingTheHint_showsTheNewMessage_andHidesTheHint() { + val arrive = showManyMessages() + scrollToTheOldest() + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + + node(ConversationScreenTags.NEW_MESSAGE_HINT).performClick() + + assertFullyInTheList(node(ConversationScreenTags.theirMessage("m50"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun scrollingDownToTheNewMessage_hidesTheHint() { + val arrive = showManyMessages() + scrollToTheOldest() + arrive(ChatMessage("m50", james.uid, "See you", manyStart)) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + + node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(0) + + node(ConversationScreenTags.theirMessage("m50")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun myNewMessageWhileReadingOlderOnes_isFollowed_withoutTheHint() { + val arrive = showManyMessages() + scrollToTheOldest() + + arrive(ChatMessage("m50", "renter", "On my way", manyStart)) + + assertFullyInTheList(node(ConversationScreenTags.myMessage("m50"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + @Test fun pausedNotice_showsWhileTheMessagesLoad() { setContent( From ad025686d3a8650d48893ef7fec676ea20d3d951 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Thu, 19 Nov 2026 04:23:09 +0100 Subject: [PATCH 3/5] fix(chat): keep the place when a photo finishes uploading or the newest message goes away A photo's message that was pending takes the place of its bubble, and a deleted newest message is not an arrival, so neither scrolls the list nor shows the hint. The hint clears once the newest message or a photo under it is in view. --- .../polybazaar/chat/ui/ConversationScreen.kt | 97 +++++++++++++++---- 1 file changed, 76 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt index abaaf5bd..9f9bebf4 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt @@ -53,6 +53,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow @@ -177,6 +178,47 @@ internal fun conversationBody(state: ConversationUiState): ConversationBody = else -> ConversationBody.EMPTY } +/** How the message list answers a change in what it shows, decided by [messageListChange]. */ +internal enum class MessageListChange { + /** Scroll to the bottom: on opening, and for the user's own message or photo. */ + FOLLOW, + /** A message from the other participant came after the newest one. */ + THEIRS_ARRIVED, + /** Nothing arrived, so the list stays where it is. */ + NONE, +} + +/** + * Classifies the change from [previousNewestId] and [previousPendingIds] to the shown [messages], + * oldest first, and the [pendingIds] of the photos being sent. A message arrived only when it comes + * after the previous newest one, which a deletion's new newest does not. A photo's message that was + * pending did not arrive either: it takes the place of its pending bubble. + * + * @param firstLoad true until the list has shown anything. + */ +internal fun messageListChange( + messages: List, + pendingIds: List, + myUid: String, + previousNewestId: String?, + previousPendingIds: List, + firstLoad: Boolean, +): MessageListChange { + if (firstLoad) return MessageListChange.FOLLOW + val sentId = pendingIds.lastOrNull() + if (sentId != null && sentId !in previousPendingIds) return MessageListChange.FOLLOW + val newest = messages.lastOrNull() ?: return MessageListChange.NONE + val arrived = + newest.id != previousNewestId && + (previousNewestId == null || messages.any { it.id == previousNewestId }) && + newest.id !in previousPendingIds + return when { + !arrived -> MessageListChange.NONE + newest.senderUid == myUid -> MessageListChange.FOLLOW + else -> MessageListChange.THEIRS_ARRIVED + } +} + /** Side margin of the page, the same as on the listing detail. */ private val PageMargin = 18.dp @@ -558,43 +600,56 @@ private fun MessageList( val messages = uiState.shownMessages val pendingPhotos = uiState.pendingPhotos val newest = messages.lastOrNull() + val pendingIds = pendingPhotos.map { it.messageId } // Item 0, at the bottom of the reversed list. val bottomKey = pendingPhotos.lastOrNull()?.let(::pendingPhotoKey) ?: newest?.id val listState = rememberLazyListState() val scope = rememberCoroutineScope() // Decoded above the list: a bubble that scrolls out of view and back shows its photo at once. val decodedPhotos = rememberDecodedPhotos(uiState.messagePhotos) - // The newest message and the bottom item already followed or hinted at, and whether a message is - // waiting below the view. Saved across recreation, as the list's position is. + // What the list showed at the last change, and whether a message is waiting below the view. + // Saved across recreation, as the list's position is; the ids in an ArrayList, which it can save. var previousNewestId by rememberSaveable { mutableStateOf(null) } + var previousPendingIds by rememberSaveable { mutableStateOf(ArrayList()) } var previousBottomKey by rememberSaveable { mutableStateOf(null) } var newestUnseen by rememberSaveable { mutableStateOf(false) } - // The list keeps its place by key, so a new message or photo arrives below the view unless this - // follows it. The user's own, a photo being sent included, is always followed. One from the - // other participant is followed only when the previous bottom item's bottom edge is on screen: - // then the user is reading the end of the conversation. Looked up by key, that item is found - // whether or not the new one is laid out yet. + // The list keeps its place by key, so an arrival lands below the view unless this follows it. + // One from the other participant is followed only when the previous bottom item's bottom edge is + // on screen: then the user is reading the end of the conversation. Looked up by key, that item is + // found whether or not the new one is laid out yet. // requestScrollToItem takes no scroll lock, so a finger on the list cannot cancel the follow. - LaunchedEffect(newest?.id, pendingPhotos.lastOrNull()?.messageId) { + LaunchedEffect(newest?.id, pendingIds) { + val change = + messageListChange( + messages = messages, + pendingIds = pendingIds, + myUid = uiState.myUid, + previousNewestId = previousNewestId, + previousPendingIds = previousPendingIds, + firstLoad = previousBottomKey == null, + ) val previousBottom = previousBottomKey - val newestChanged = newest != null && newest.id != previousNewestId - if (!newestChanged && bottomKey == previousBottom) return@LaunchedEffect - val layout = listState.layoutInfo - val follow = - previousBottom == null || - (bottomKey != previousBottom && pendingPhotos.isNotEmpty()) || - (newestChanged && newest.senderUid == uiState.myUid) || + previousNewestId = newest?.id + previousPendingIds = ArrayList(pendingIds) + previousBottomKey = bottomKey + when (change) { + MessageListChange.FOLLOW -> listState.requestScrollToItem(0) + MessageListChange.THEIRS_ARRIVED -> { + val layout = listState.layoutInfo + val atTheEnd = layout.visibleItemsInfo.any { it.key == previousBottom && it.offset >= layout.viewportStartOffset } - previousNewestId = newest?.id - previousBottomKey = bottomKey - if (follow) listState.requestScrollToItem(0) else if (newestChanged) newestUnseen = true + if (atTheEnd) listState.requestScrollToItem(0) else newestUnseen = true + } + MessageListChange.NONE -> Unit + } } - // Item 0 is the bottom one. The hint goes only once that is in view, so a tap whose scroll is - // cut short leaves it up. + // The photos being sent are the items under the newest message. The hint goes only once that + // message or one of them is in view, so a tap whose scroll is cut short leaves it up. + val pendingCount by rememberUpdatedState(pendingPhotos.size) LaunchedEffect(listState) { - snapshotFlow { newestUnseen && listState.firstVisibleItemIndex == 0 } + snapshotFlow { newestUnseen && listState.firstVisibleItemIndex <= pendingCount } .collect { seen -> if (seen) newestUnseen = false } } Column(modifier = Modifier.fillMaxSize()) { From 77257ed84a810f3fb4bdb1f19f12ed561fd5dd45 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Thu, 19 Nov 2026 04:23:09 +0100 Subject: [PATCH 4/5] test(chat): cover the message list with photos being sent --- .../chat/ui/ConversationScreenTest.kt | 164 ++++++++++++++++-- .../chat/ui/MessageListChangeTest.kt | 122 +++++++++++++ 2 files changed, 271 insertions(+), 15 deletions(-) create mode 100644 app/src/test/java/com/android/polybazaar/chat/ui/MessageListChangeTest.kt diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt index 9b58381c..a106250e 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt @@ -47,6 +47,7 @@ import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollToIndex +import androidx.compose.ui.test.performScrollToNode import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performTextReplacement import androidx.compose.ui.test.performTouchInput @@ -235,12 +236,22 @@ class ConversationScreenTest { return { message -> uiState = uiState.copy(messages = uiState.messages + message) } } - /** Scrolls up to the oldest of [manyMessages], the last item of the list. */ + /** Scrolls up to the oldest of [manyMessages], at the top of the list. */ private fun scrollToTheOldest() { - node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(manyMessages.lastIndex) + node(ConversationScreenTags.MESSAGE_LIST) + .performScrollToNode(hasTestTag(ConversationScreenTags.myMessage("m0"))) node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() } + /** Shows [state], and returns how to change it. */ + private fun showChanging( + state: ConversationUiState + ): ((ConversationUiState) -> ConversationUiState) -> Unit { + var uiState by mutableStateOf(state) + composeTestRule.setContent { ConversationContent(uiState = uiState, zone = ZoneOffset.UTC) } + return { change -> uiState = change(uiState) } + } + /** Every text of the empty state. */ private fun emptyStateTexts() = composeTestRule.onAllNodes( @@ -656,39 +667,162 @@ class ConversationScreenTest { } @Test - fun photoSentWhileReadingOlderOnes_isFollowed_withoutTheHint() { - var uiState by mutableStateOf(loaded.copy(messages = manyMessages)) - composeTestRule.setContent { ConversationContent(uiState = uiState, zone = ZoneOffset.UTC) } + fun photoSentWhileReadingOlderOnes_isFollowed() { + val change = showChanging(loaded.copy(messages = manyMessages)) scrollToTheOldest() - uiState = - uiState.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50"))) + change { it.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50"))) } assertFullyInTheList(node(ConversationScreenTags.pendingPhoto("m50"))) - node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() } @Test - fun theirNewMessageWhileAPhotoSendsAtTheEnd_isFollowed_withoutTheHint() { - var uiState by - mutableStateOf( + fun theirNewMessageWhileAPhotoSendsAtTheEnd_staysAboveThePhoto_withoutTheHint() { + val change = + showChanging( loaded.copy( messages = manyMessages, pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50")), ) ) - composeTestRule.setContent { ConversationContent(uiState = uiState, zone = ZoneOffset.UTC) } assertFullyInTheList(node(ConversationScreenTags.pendingPhoto("m50"))) - uiState = - uiState.copy(messages = manyMessages + ChatMessage("m51", james.uid, "Nice", manyStart)) + change { it.copy(messages = manyMessages + ChatMessage("m51", james.uid, "Nice", manyStart)) } - // The photo being sent stays last, under the new message. assertFullyInTheList(node(ConversationScreenTags.pendingPhoto("m50"))) node(ConversationScreenTags.theirMessage("m51")).assertIsDisplayed() node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() } + @Test + fun uploadFinishingWhileReadingOlderOnes_keepsThePlace_withoutTheHint() { + val change = + showChanging( + loaded.copy( + messages = manyMessages + photoMessage("m50", "renter"), + pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50")), + ) + ) + scrollToTheOldest() + + change { it.copy(pendingPhotos = emptyList()) } + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.myMessage("m50")).assertIsNotDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun newerPhotoFinishingAboveAFailedOneWhileReadingOlderOnes_keepsThePlace() { + val change = + showChanging( + loaded.copy( + messages = + manyMessages + photoMessage("m50", "renter") + photoMessage("m51", "renter"), + pendingPhotos = + listOf( + pending(PendingPhotoStatus.FAILED, AppError.NETWORK, id = "m50"), + pending(PendingPhotoStatus.UPLOADING, id = "m51"), + ), + ) + ) + scrollToTheOldest() + + change { it.copy(pendingPhotos = it.pendingPhotos.dropLast(1)) } + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.myMessage("m51")).assertIsNotDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + // A window taller than a photo bubble, so the photo and the messages around it fit together. + @Test + @Config(qualifiers = "w360dp-h800dp") + fun uploadFinishingAtTheEnd_staysAtTheEnd() { + val change = + showChanging( + loaded.copy( + messages = manyMessages + photoMessage("m50", "renter"), + pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING, id = "m50")), + ) + ) + assertFullyInTheList(node(ConversationScreenTags.pendingPhoto("m50"))) + + change { it.copy(pendingPhotos = emptyList()) } + + assertFullyInTheList(node(ConversationScreenTags.myMessage("m50"))) + } + + @Test + fun newestMessageDeletedWhileReadingOlderOnes_withTheirsNowNewest_keepsThePlace_withoutTheHint() { + val change = + showChanging( + loaded.copy(messages = manyMessages + ChatMessage("m50", "renter", "Photo", manyStart)) + ) + scrollToTheOldest() + + change { it.copy(messages = manyMessages) } + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + fun newestMessageDeletedWhileReadingOlderOnes_withMineNowNewest_keepsThePlace() { + val change = showChanging(loaded.copy(messages = manyMessages)) + scrollToTheOldest() + + change { it.copy(messages = manyMessages.dropLast(1)) } + + node(ConversationScreenTags.myMessage("m0")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + @Config(qualifiers = "w360dp-h800dp") + fun theirNewMessageFullyInViewAboveAFailedPhoto_hidesTheHint() { + val change = + showChanging( + loaded.copy( + messages = manyMessages, + pendingPhotos = + listOf(pending(PendingPhotoStatus.FAILED, AppError.NETWORK, id = "m50")), + ) + ) + scrollToTheOldest() + change { it.copy(messages = manyMessages + ChatMessage("m51", james.uid, "Nice", manyStart)) } + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertIsDisplayed() + + // The new message first from the bottom, the failed photo under it scrolled away. + node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(1) + + assertFullyInTheList(node(ConversationScreenTags.theirMessage("m51"))) + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + + @Test + @Config(qualifiers = "w360dp-h800dp") + fun theirNewMessageLandingInViewAboveTwoFailedPhotos_leavesNoHint() { + val change = + showChanging( + loaded.copy( + messages = manyMessages, + pendingPhotos = + listOf( + pending(PendingPhotoStatus.FAILED, AppError.NETWORK, id = "m50"), + pending(PendingPhotoStatus.FAILED, AppError.NETWORK, id = "m51"), + ), + ) + ) + // The upper failed photo first from the bottom, the lower one scrolled away. + node(ConversationScreenTags.MESSAGE_LIST).performScrollToIndex(1) + + change { it.copy(messages = manyMessages + ChatMessage("m52", james.uid, "Nice", manyStart)) } + + node(ConversationScreenTags.theirMessage("m52")).assertIsDisplayed() + node(ConversationScreenTags.NEW_MESSAGE_HINT).assertDoesNotExist() + } + @Test fun pausedNotice_showsWhileTheMessagesLoad() { setContent( diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/MessageListChangeTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/MessageListChangeTest.kt new file mode 100644 index 00000000..45a59eb9 --- /dev/null +++ b/app/src/test/java/com/android/polybazaar/chat/ui/MessageListChangeTest.kt @@ -0,0 +1,122 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.chat.ui + +import com.android.polybazaar.chat.model.ChatMessage +import java.time.Instant +import org.junit.Assert.assertEquals +import org.junit.Test + +class MessageListChangeTest { + + private val sentAt = Instant.parse("2026-11-11T09:00:00Z") + + private fun mine(id: String) = ChatMessage(id, "renter", "Mine", sentAt) + + private fun theirs(id: String) = ChatMessage(id, "lender", "Theirs", sentAt) + + private val shown = listOf(mine("m1"), theirs("m2")) + + /** The change to [messages] and [pendingIds] from [shown] with nothing pending, by default. */ + private fun change( + messages: List, + pendingIds: List = emptyList(), + previousNewestId: String? = "m2", + previousPendingIds: List = emptyList(), + firstLoad: Boolean = false, + ) = + messageListChange( + messages = messages, + pendingIds = pendingIds, + myUid = "renter", + previousNewestId = previousNewestId, + previousPendingIds = previousPendingIds, + firstLoad = firstLoad, + ) + + @Test + fun firstLoad_follows() { + assertEquals( + MessageListChange.FOLLOW, + change(shown, previousNewestId = null, firstLoad = true), + ) + } + + @Test + fun nothingNew_isNone() { + assertEquals(MessageListChange.NONE, change(shown)) + } + + @Test + fun theirMessageAfterTheNewest_arrives() { + assertEquals(MessageListChange.THEIRS_ARRIVED, change(shown + theirs("m3"))) + } + + @Test + fun myMessageAfterTheNewest_follows() { + assertEquals(MessageListChange.FOLLOW, change(shown + mine("m3"))) + } + + @Test + fun theirMessageWhenOnlyAPhotoWasShown_arrives() { + assertEquals( + MessageListChange.THEIRS_ARRIVED, + change( + listOf(theirs("m2")), + pendingIds = listOf("m1"), + previousNewestId = null, + previousPendingIds = listOf("m1"), + ), + ) + } + + @Test + fun photoBeingSent_follows() { + assertEquals(MessageListChange.FOLLOW, change(shown, pendingIds = listOf("m3"))) + } + + @Test + fun anotherPhotoBeingSentAfterAFailedOne_follows() { + assertEquals( + MessageListChange.FOLLOW, + change(shown, pendingIds = listOf("m3", "m4"), previousPendingIds = listOf("m3")), + ) + } + + @Test + fun uploadFinished_revealsThePhotoWithoutAnArrival() { + assertEquals( + MessageListChange.NONE, + change(shown + mine("m3"), previousPendingIds = listOf("m3")), + ) + } + + @Test + fun newerPhotoFinishedAboveAFailedOne_isNone() { + assertEquals( + MessageListChange.NONE, + change( + shown + mine("m4"), + pendingIds = listOf("m3"), + previousPendingIds = listOf("m3", "m4"), + ), + ) + } + + @Test + fun lastPhotoDiscarded_isNone() { + assertEquals( + MessageListChange.NONE, + change(shown, pendingIds = listOf("m3"), previousPendingIds = listOf("m3", "m4")), + ) + } + + @Test + fun newestDeleted_withTheirsNowNewest_isNone() { + assertEquals(MessageListChange.NONE, change(shown, previousNewestId = "m3")) + } + + @Test + fun newestDeleted_withMineNowNewest_isNone() { + assertEquals(MessageListChange.NONE, change(listOf(mine("m1")))) + } +} From d65e22b78414ca06a6132062ba37cd8be45880f5 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Thu, 19 Nov 2026 20:12:57 +0100 Subject: [PATCH 5/5] fix(chat): clear the new-message hint by key, whatever the layout order The hint goes once the newest message or a photo being sent under it is on screen, looked up by key, so it holds whether or not the new message has been laid out when the hint is set. --- .../polybazaar/chat/ui/ConversationScreen.kt | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt index 9f9bebf4..c82e3b87 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt @@ -645,11 +645,21 @@ private fun MessageList( MessageListChange.NONE -> Unit } } - // The photos being sent are the items under the newest message. The hint goes only once that - // message or one of them is in view, so a tap whose scroll is cut short leaves it up. - val pendingCount by rememberUpdatedState(pendingPhotos.size) + // The hint goes once the newest message, or a photo being sent under it, is in view; a tap whose + // scroll is cut short leaves it up. Looked up by key, which holds whether or not the new message + // is laid out yet. + val endKeys by + rememberUpdatedState(setOfNotNull(newest?.id) + pendingPhotos.map(::pendingPhotoKey)) LaunchedEffect(listState) { - snapshotFlow { newestUnseen && listState.firstVisibleItemIndex <= pendingCount } + snapshotFlow { + if (!newestUnseen) return@snapshotFlow false + val layout = listState.layoutInfo + layout.visibleItemsInfo.any { + it.key in endKeys && + it.offset + it.size > layout.viewportStartOffset && + it.offset < layout.viewportEndOffset + } + } .collect { seen -> if (seen) newestUnseen = false } } Column(modifier = Modifier.fillMaxSize()) {