From d3ea479780cf9ec2d1dd56a7bdca49b3b2f181fa Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Tue, 17 Nov 2026 17:18:45 +0100 Subject: [PATCH 01/16] feat(chat): download the photos of the messages Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt index 211d8019..aacfd6ee 100644 --- a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt @@ -81,6 +81,9 @@ data class PendingPhoto( * conversation loads and after it failed to load, when whether it exists is unknown. * @property pendingPhotos the photos sent that are still uploading or failed, oldest first. Their * message may already be in [messages], since it is written before the photo is uploaded. + * @property messagePhotos the photos of [messages] downloaded so far, by [ChatMessage.imagePath]. + * @property photoLoadErrors why the photo at each path could not be downloaded; + * [ConversationViewModel.loadPhoto] tries again. * @property isLoading true until the listing, the conversation and the messages have each been * loaded or failed, and again while a retry reloads any of them. * @property loadError why the conversation could not be loaded; the screen offers Retry. What is @@ -100,6 +103,8 @@ data class ConversationUiState( val canSend: Boolean = false, val firstMessageBlockedByPause: Boolean = false, val pendingPhotos: List = emptyList(), + val messagePhotos: Map = emptyMap(), + val photoLoadErrors: Map = emptyMap(), val isLoading: Boolean = true, val loadError: AppError? = null, val sendError: AppError? = null, @@ -184,6 +189,8 @@ class ConversationViewModel( // Photos taken with the camera and not deleted yet, so gallery photos are never deleted. private val takenPhotos = mutableSetOf() + // The message photos being downloaded, so that no photo is downloaded twice at once. + private val photosDownloading = mutableSetOf() init { observeListing() @@ -388,6 +395,28 @@ class ConversationViewModel( abandon(failed) } + /** + * Downloads the photo of a message at [path], its [ChatMessage.imagePath], unless it is already + * downloaded or downloading. A message's photo never changes, so it is downloaded once. After a + * failure, calling it again clears the error and tries again. + */ + fun loadPhoto(path: String) { + if (path in _uiState.value.messagePhotos || !photosDownloading.add(path)) return + _uiState.update { it.copy(photoLoadErrors = it.photoLoadErrors - path) } + viewModelScope.launch { + try { + val photo = chatRepository.loadMessagePhoto(path) + _uiState.update { it.copy(messagePhotos = it.messagePhotos + (path to photo)) } + } catch (exception: Exception) { + if (exception is CancellationException) throw exception + val error = exception.toAppError() + _uiState.update { it.copy(photoLoadErrors = it.photoLoadErrors + (path to error)) } + } finally { + photosDownloading.remove(path) + } + } + } + fun dismissSendError() { _uiState.update { it.copy(sendError = null) } } From e62172b54e0a576e41fc16c16112f7aefd887799 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:48:13 +0100 Subject: [PATCH 02/16] feat(chat): show the photos of the messages Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 210 +++++++++++++++++- app/src/main/res/values/strings.xml | 2 + 2 files changed, 201 insertions(+), 11 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 3efe6947..d6bfe4c9 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 @@ -8,6 +8,7 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -89,6 +90,7 @@ import com.android.polybazaar.chat.viewmodel.PendingPhotoStatus import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message import com.android.polybazaar.listing.ui.CameraPermissionDialog +import com.android.polybazaar.listing.ui.decodePhotoPreview import com.android.polybazaar.listing.ui.loadPhotoPreview import com.android.polybazaar.listing.ui.rememberPhotoCamera import java.time.Instant @@ -126,6 +128,12 @@ object ConversationScreenTags { /** Tag of the bubble of the other participant's message with [id]. */ fun theirMessage(id: String) = "conversation_their_message_$id" + /** Tag of the photo of the message with [id], or of its placeholder while it loads. */ + fun messagePhoto(id: String) = "conversation_message_photo_$id" + + /** Tag of the placeholder of the message with [id] whose photo failed to load; tap to retry. */ + fun photoLoadError(id: String) = "conversation_photo_load_error_$id" + /** Tag of the bubble of the photo being sent, or that failed, with message ID [id]. */ fun pendingPhoto(id: String) = "conversation_pending_photo_$id" @@ -170,6 +178,9 @@ private val MaxBubbleWidth = 300.dp */ private val BubblePhotoHeight = 200.dp +/** Longest side, in pixels, a message photo is decoded at: sharp across a bubble. */ +private const val BUBBLE_PHOTO_MAX_SIZE = 1024 + private val TimeFormat = DateTimeFormatter.ofPattern("HH:mm") /** @@ -213,6 +224,7 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { ) }, onRemoveAttachedPhoto = viewModel::removeAttachedPhoto, + onLoadPhoto = viewModel::loadPhoto, onRetryPhoto = viewModel::retryPhoto, onDiscardPhoto = viewModel::discardPhoto, ) @@ -237,6 +249,8 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { * @param onTakePhoto called when the user picks "Take photo" in the photo menu. * @param onChoosePhoto called when the user picks "Choose from gallery" in the photo menu. * @param onRemoveAttachedPhoto called when the user taps ✕ on the attached photo. + * @param onLoadPhoto called with a message's imagePath when its bubble shows and the photo is + * neither downloaded nor failed, and when the user taps a photo that failed to load. * @param onRetryPhoto called with the message ID of a failed photo when the user taps Retry. * @param onDiscardPhoto called with the message ID of a failed photo when the user taps Remove. * @param zone time zone of the message times. @@ -252,6 +266,7 @@ fun ConversationContent( onTakePhoto: () -> Unit = {}, onChoosePhoto: () -> Unit = {}, onRemoveAttachedPhoto: () -> Unit = {}, + onLoadPhoto: (String) -> Unit = {}, onRetryPhoto: (String) -> Unit = {}, onDiscardPhoto: (String) -> Unit = {}, zone: ZoneId = ZoneId.systemDefault(), @@ -292,7 +307,7 @@ fun ConversationContent( uiState = uiState, zone = zone, onRetry = onRetry, - photoActions = PhotoActions(onRetryPhoto, onDiscardPhoto), + photoActions = PhotoActions(onLoadPhoto, onRetryPhoto, onDiscardPhoto), ) } } @@ -504,8 +519,9 @@ private fun EmptyState( } } -/** What the user can do with the photos being sent. */ +/** What the user can do with the photos in the conversation. */ private class PhotoActions( + val load: (path: String) -> Unit, val retry: (messageId: String) -> Unit, val discard: (messageId: String) -> Unit, ) @@ -554,6 +570,14 @@ private fun MessageList( isMine = message.senderUid == uiState.myUid, otherUsername = uiState.otherUser?.username, zone = zone, + photo = + message.imagePath?.let { path -> + MessagePhoto( + bytes = uiState.messagePhotos[path], + failed = path in uiState.photoLoadErrors, + load = { photoActions.load(path) }, + ) + }, ) } } @@ -592,8 +616,15 @@ private fun LoadErrorRow(text: String, onRetry: () -> Unit) { } /** - * One message: the user's own at the end of the row, the other participant's at the start. The - * footer says who sent it and when, or only when while the other participant's profile is unknown. + * The photo of a message: its downloaded [bytes], or null until they arrive; [failed] when the + * download failed. [load] asks for it. + */ +private class MessagePhoto(val bytes: ByteArray?, val failed: Boolean, val load: () -> Unit) + +/** + * One message: the user's own at the end of the row, the other participant's at the start. A photo + * message shows its photo, then its caption if any. The footer says who sent it and when, or only + * when while the other participant's profile is unknown. */ @Composable private fun MessageBubble( @@ -601,6 +632,7 @@ private fun MessageBubble( isMine: Boolean, otherUsername: String?, zone: ZoneId, + photo: MessagePhoto?, ) { val time = message.sentAt.atZone(zone).format(TimeFormat) val footer = @@ -615,14 +647,19 @@ private fun MessageBubble( tag = if (isMine) ConversationScreenTags.myMessage(message.id) else ConversationScreenTags.theirMessage(message.id), - fixedWidth = false, + // A photo bubble takes its full width at once, so it does not grow when the photo arrives. + fixedWidth = photo != null, ) { - Text( - text = message.text, - color = AuthColors.TextPrimary, - fontSize = 14.sp, - lineHeight = 19.sp, - ) + photo?.let { BubblePhoto(messageId = message.id, photo = it) } + // A photo alone has no text. + if (message.text.isNotEmpty()) { + Text( + text = message.text, + color = AuthColors.TextPrimary, + fontSize = 14.sp, + lineHeight = 19.sp, + ) + } BubbleFooter(text = footer) } } @@ -676,6 +713,109 @@ private fun ColumnScope.BubbleFooter(text: String) { ) } +/** A message photo after it is decoded, or why it is not shown. */ +private sealed interface DecodedPhoto { + data object Loading : DecodedPhoto + + data object Failed : DecodedPhoto + + class Shown(val bitmap: ImageBitmap) : DecodedPhoto +} + +/** + * The photo of a message, asked for when the bubble first shows: a placeholder of the same size + * while it downloads and decodes, and one that offers to try again when it could not be loaded. + */ +@Composable +private fun BubblePhoto(messageId: String, photo: MessagePhoto) { + // Not asked again on its own after a failure: only when the user taps to retry. + LaunchedEffect(messageId) { if (photo.bytes == null && !photo.failed) photo.load() } + val decoded by + produceState(initialValue = DecodedPhoto.Loading, photo.bytes) { + val bytes = photo.bytes + value = + if (bytes == null) DecodedPhoto.Loading + else + decodePhotoPreview(bytes, maxSize = BUBBLE_PHOTO_MAX_SIZE)?.let { + DecodedPhoto.Shown(it) + } ?: DecodedPhoto.Failed + } + val description = stringResource(R.string.conversation_photo) + val shape = RoundedCornerShape(10.dp) + val modifier = + Modifier.fillMaxWidth() + .height(BubblePhotoHeight) + .clip(shape) + .testTag(ConversationScreenTags.messagePhoto(messageId)) + val current = decoded + when { + current is DecodedPhoto.Shown -> + Image( + bitmap = current.bitmap, + contentDescription = description, + contentScale = ContentScale.Crop, + modifier = modifier, + ) + // Undecodable bytes would fail again, so only a failed download offers to retry. + photo.failed || current is DecodedPhoto.Failed -> + PhotoLoadError( + onRetry = photo.load.takeIf { photo.failed }, + modifier = + modifier.then( + if (photo.failed) + Modifier.testTag(ConversationScreenTags.photoLoadError(messageId)) + else Modifier + ), + ) + else -> + Box( + modifier = + modifier.background(AuthColors.Outline).semantics { + contentDescription = description + }, + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator( + color = AuthColors.TextSecondary, + strokeWidth = 2.dp, + modifier = Modifier.size(20.dp), + ) + } + } +} + +/** A photo that could not be loaded, with "tap to retry" when [onRetry] is given. */ +@Composable +private fun PhotoLoadError(onRetry: (() -> Unit)?, modifier: Modifier) { + Column( + modifier = + modifier + .background(AuthColors.Outline) + .then(if (onRetry != null) Modifier.clickable(onClick = onRetry) else Modifier) + .padding(12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterVertically), + ) { + // Decorative: the text under it says what happened. + Icon( + painter = painterResource(R.drawable.ic_image), + contentDescription = null, + tint = AuthColors.TextSecondary, + modifier = Modifier.size(20.dp), + ) + Text( + text = + stringResource( + if (onRetry != null) R.string.conversation_photo_load_failed_retry + else R.string.conversation_photo_load_failed + ), + color = AuthColors.TextSecondary, + fontSize = 11.sp, + textAlign = TextAlign.Center, + ) + } +} + /** * A photo the user sent that is not in the conversation yet, as their own bubble: faded with a * spinner while it uploads; faded with why it failed, Retry and Remove once it failed. @@ -1078,3 +1218,51 @@ internal fun ConversationContentPreview() { zone = ZoneOffset.UTC, ) } + +/** A photo from the other participant still loading, and one of mine that failed to send. */ +@Preview(showBackground = true, widthDp = 412, heightDp = 917) +@Composable +internal fun ConversationPhotosPreview() { + val start = Instant.parse("2026-05-04T09:12:00Z") + ConversationContent( + uiState = + ConversationUiState( + myUid = "renter", + messages = + listOf( + ChatMessage("1", "renter", "Could you send a photo of the drill?", start), + ChatMessage( + "2", + "lender", + "Here it is, with both batteries.", + start.plusSeconds(120), + imagePath = "conversations/drill_renter/2.jpg", + ), + ), + conversation = + Conversation( + listingId = "drill", + listingTitle = "Bosch drill set", + renterUid = "renter", + lenderUid = "lender", + lastMessageAt = start.plusSeconds(120), + ), + listingTitle = "Bosch drill set", + listingStatus = ConversationListingStatus.ACTIVE, + otherUser = User(uid = "lender", email = "", username = "james"), + canAttachPhoto = true, + pendingPhotos = + listOf( + PendingPhoto( + messageId = "3", + photo = Uri.parse("content://media/photo/3"), + caption = "And the shelf I mean", + status = PendingPhotoStatus.FAILED, + error = AppError.NETWORK, + ) + ), + isLoading = false, + ), + zone = ZoneOffset.UTC, + ) +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d62ee84e..3bd451ea 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -99,6 +99,8 @@ Attached photo Remove photo Photo + Couldn’t load the photo · Tap to retry + Couldn’t load the photo Sending… Not sent. %1$s Remove From ddbdb28d9554c91afcec7d06b4c6622e9d92d575 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 02:07:29 +0100 Subject: [PATCH 03/16] feat(chat): wait for a photo that is still uploading A photo's message reaches the conversation before the photo reaches Storage, so a download that finds no photo now keeps the bubble loading and tries again for about 30 s instead of failing. When this device finishes sending a photo, its bubble tries again at once. Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 50 +++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt index aacfd6ee..a0b7a0ca 100644 --- a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt @@ -20,15 +20,26 @@ import com.android.polybazaar.listing.model.PhotoStorage import com.android.polybazaar.profile.model.ProfileRepository import java.time.Instant import java.util.concurrent.atomic.AtomicBoolean +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull + +/** + * How long to wait before each new try at a message photo that is not in Storage yet: a photo's + * message reaches the conversation before the photo, which may still be uploading. About 30 s in + * all, as long as a send may take before it gives up. + */ +private val PhotoUploadWaits = listOf(1, 2, 4, 8, 15).map { it.seconds } /** What the listing a conversation is about has become. */ enum class ConversationListingStatus { @@ -191,6 +202,8 @@ class ConversationViewModel( private val takenPhotos = mutableSetOf() // The message photos being downloaded, so that no photo is downloaded twice at once. private val photosDownloading = mutableSetOf() + // The paths of the photos this device just finished sending, to stop waiting for them at once. + private val sentPhotoPaths = MutableSharedFlow(extraBufferCapacity = 8) init { observeListing() @@ -356,6 +369,7 @@ class ConversationViewModel( } // Sent: nothing can fail any more, so the taken photo is no longer needed. deleteIfTaken(pending.photo) + showSentPhoto(pending.messageId) } catch (exception: Exception) { if (exception is CancellationException) throw exception // A refusal from a pause or deletion of the listing also reaches its observation, which @@ -397,15 +411,16 @@ class ConversationViewModel( /** * Downloads the photo of a message at [path], its [ChatMessage.imagePath], unless it is already - * downloaded or downloading. A message's photo never changes, so it is downloaded once. After a - * failure, calling it again clears the error and tries again. + * downloaded or downloading. A message's photo never changes, so it is downloaded once. A photo + * not in Storage yet is still loading, not failed: it is tried again for a while, since it may + * still be uploading. After a failure, calling it again clears the error and tries again. */ fun loadPhoto(path: String) { if (path in _uiState.value.messagePhotos || !photosDownloading.add(path)) return _uiState.update { it.copy(photoLoadErrors = it.photoLoadErrors - path) } viewModelScope.launch { try { - val photo = chatRepository.loadMessagePhoto(path) + val photo = downloadOnceUploaded(path) _uiState.update { it.copy(messagePhotos = it.messagePhotos + (path to photo)) } } catch (exception: Exception) { if (exception is CancellationException) throw exception @@ -417,6 +432,35 @@ class ConversationViewModel( } } + /** + * Downloads the photo at [path]. While Storage answers NOT_FOUND, waits [PhotoUploadWaits] in + * turn and tries again, or at once when this device finishes sending that photo. Any other + * failure, or a photo still missing after the last wait, is thrown. + */ + private suspend fun downloadOnceUploaded(path: String): ByteArray { + for (wait in PhotoUploadWaits) { + try { + return chatRepository.loadMessagePhoto(path) + } catch (exception: Exception) { + if (exception is CancellationException || exception.toAppError() != AppError.NOT_FOUND) { + throw exception + } + } + withTimeoutOrNull(wait) { sentPhotoPaths.first { it == path } } + } + return chatRepository.loadMessagePhoto(path) + } + + /** + * Shows the photo of the message [messageId] this device just sent, now in Storage: a download + * waiting for it tries again at once, and one that already gave up starts again. + */ + private fun showSentPhoto(messageId: String) { + val state = _uiState.value + val path = state.messages.firstOrNull { it.id == messageId }?.imagePath ?: return + if (path in state.photoLoadErrors) loadPhoto(path) else sentPhotoPaths.tryEmit(path) + } + fun dismissSendError() { _uiState.update { it.copy(sendError = null) } } From a62030e475c738c666cd9a28cf63be1bb37a0eda Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 02:12:51 +0100 Subject: [PATCH 04/16] feat(chat): show "Photo" for a photo message in the inbox A photo sent without a caption previews as an empty text, so its inbox row shows "Photo" with a small image icon instead of an empty line. Co-Authored-By: Claude Opus 5.5 --- .../android/polybazaar/chat/ui/InboxScreen.kt | 38 ++++++++++++++----- app/src/main/res/values/strings.xml | 1 + 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt index 8a659be2..c74abe61 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt @@ -415,16 +415,34 @@ private fun LastMessagePreview( isUnread: Boolean, conversationId: String, ) { - Text( - text = if (isMine) stringResource(R.string.inbox_last_message_mine, text) else text, - color = if (isUnread) AuthColors.TextPrimary else AuthColors.TextSecondary, - fontSize = 13.sp, - lineHeight = 18.sp, - fontWeight = if (isUnread) FontWeight.SemiBold else FontWeight.Normal, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.testTag(InboxScreenTags.preview(conversationId)), - ) + // A photo sent alone previews as an empty text. + val isPhoto = text.isEmpty() + val shown = if (isPhoto) stringResource(R.string.inbox_last_message_photo) else text + val color = if (isUnread) AuthColors.TextPrimary else AuthColors.TextSecondary + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (isPhoto) { + // Decorative: the text says "Photo". + Icon( + painter = painterResource(R.drawable.ic_image), + contentDescription = null, + tint = color, + modifier = Modifier.size(14.dp), + ) + } + Text( + text = if (isMine) stringResource(R.string.inbox_last_message_mine, shown) else shown, + color = color, + fontSize = 13.sp, + lineHeight = 18.sp, + fontWeight = if (isUnread) FontWeight.SemiBold else FontWeight.Normal, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.testTag(InboxScreenTags.preview(conversationId)), + ) + } } /** diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3bd451ea..bbf27199 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -178,6 +178,7 @@ Found something you like?\nOpen a listing and message its owner.\nYour conversations will appear here. Browse listings You: %1$s + Photo Unread From 5f1b514ee7c56c367972dfe217bca454321d117c Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:04:26 +0100 Subject: [PATCH 05/16] test(chat): cover downloading message photos Co-Authored-By: Claude Opus 5.5 --- .../viewmodel/ConversationViewModelTest.kt | 173 +++++++++++++++++- 1 file changed, 172 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt index cb21bac2..be02f0e2 100644 --- a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt @@ -10,6 +10,7 @@ import androidx.lifecycle.viewmodel.viewModelFactory import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.auth.model.User import com.android.polybazaar.chat.model.ChatMessage +import com.android.polybazaar.chat.model.ChatRepository import com.android.polybazaar.chat.model.ChatRules import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.model.FakeChatRepository @@ -24,6 +25,7 @@ import com.android.polybazaar.profile.model.FakeProfileRepository import com.google.firebase.firestore.FirebaseFirestoreException import java.net.UnknownHostException import java.time.Instant +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -33,6 +35,7 @@ import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After +import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull @@ -53,6 +56,7 @@ class ConversationViewModelTest { private lateinit var profiles: FakeProfileRepository private lateinit var listings: FakeListingRepository private lateinit var photoStorage: FakePhotoStorage + private lateinit var downloads: CountingDownloads private val lender = User(uid = "lender", email = "", username = "Lena") private val renter = User(uid = "renter", email = "", username = "Remi") @@ -108,7 +112,7 @@ class ConversationViewModelTest { listing.listingId!!, renter.uid, myUid, - chat, + CountingDownloads(chat).also { downloads = it }, profiles, listings, photoStorage, @@ -1753,6 +1757,173 @@ class ConversationViewModelTest { assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) } + private val photoPath = "chats/drill_renter/m1.jpg" + private val photoBytes = byteArrayOf(1, 2, 3) + private val missing = AppException(AppError.NOT_FOUND) + + /** Remi's photo message "m1", the id the fake gives the next photo sent. */ + private val photoMessage = + ChatMessage("m1", renter.uid, "", Instant.ofEpochSecond(300), imagePath = photoPath) + + /** Runs what is due now without moving the virtual clock. */ + private fun runCurrent() = testDispatcher.scheduler.runCurrent() + + private fun advanceBy(millis: Long) { + testDispatcher.scheduler.advanceTimeBy(millis) + runCurrent() + } + + /** The photo is in Storage now. */ + private fun uploaded() { + chat.photoLoadFailure = null + chat.photos[photoPath] = photoBytes + } + + @Test + fun loadPhoto_putsTheBytesInMessagePhotos() { + uploaded() + val viewModel = inConversation() + + viewModel.loadPhoto(photoPath) + advance() + + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + } + + @Test + fun loadPhoto_twiceWhileDownloading_downloadsOnce() { + uploaded() + val viewModel = inConversation() + + viewModel.loadPhoto(photoPath) + viewModel.loadPhoto(photoPath) + advance() + + assertEquals(listOf(photoPath), downloads.loads) + } + + @Test + fun loadPhoto_onceDownloaded_doesNotDownloadAgain() { + uploaded() + val viewModel = inConversation() + viewModel.loadPhoto(photoPath) + advance() + + viewModel.loadPhoto(photoPath) + advance() + + assertEquals(listOf(photoPath), downloads.loads) + } + + @Test + fun loadPhoto_failing_recordsTheErrorAtOnce_withoutWaiting() { + chat.photoLoadFailure = firestoreError(FirebaseFirestoreException.Code.UNAVAILABLE) + val viewModel = inConversation() + + viewModel.loadPhoto(photoPath) + runCurrent() + + assertEquals(mapOf(photoPath to AppError.NETWORK), viewModel.uiState.value.photoLoadErrors) + assertEquals(1, downloads.loads.size) + } + + @Test + fun loadPhoto_afterAFailure_clearsTheErrorAndDownloadsAgain() { + chat.photoLoadFailure = firestoreError(FirebaseFirestoreException.Code.UNAVAILABLE) + val viewModel = inConversation() + viewModel.loadPhoto(photoPath) + advance() + uploaded() + + viewModel.loadPhoto(photoPath) + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + advance() + + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + } + + @Test + fun loadPhoto_notFoundYet_staysLoading_andArrivesOnALaterTry() { + chat.photoLoadFailure = missing + val viewModel = inConversation() + viewModel.loadPhoto(photoPath) + runCurrent() + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + assertEquals(emptyMap(), viewModel.uiState.value.messagePhotos) + + uploaded() + advanceBy(999) + assertEquals(1, downloads.loads.size) + advanceBy(1) + + assertEquals(2, downloads.loads.size) + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + } + + @Test + fun loadPhoto_stillNotFound_recordsTheErrorOnlyAfterTheLastWait() { + chat.photoLoadFailure = missing + val viewModel = inConversation() + viewModel.loadPhoto(photoPath) + runCurrent() + + // 1 + 2 + 4 + 8 + 15 s. + val allWaits = 30.seconds.inWholeMilliseconds + advanceBy(allWaits - 1) + assertEquals(5, downloads.loads.size) + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + advanceBy(1) + + assertEquals(6, downloads.loads.size) + assertEquals(mapOf(photoPath to AppError.NOT_FOUND), viewModel.uiState.value.photoLoadErrors) + } + + @Test + fun myPhotoSent_wakesADownloadWaitingForIt() { + givenConversation(messages = arrayOf(photoMessage)) + chat.photoLoadFailure = missing + val viewModel = loadedViewModel() + viewModel.loadPhoto(photoPath) + runCurrent() + viewModel.attachPhoto(galleryPhoto) + + uploaded() + viewModel.send() + runCurrent() + + assertEquals(2, downloads.loads.size) + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + } + + @Test + fun myPhotoSent_restartsADownloadThatGaveUp() { + givenConversation(messages = arrayOf(photoMessage)) + chat.photoLoadFailure = missing + val viewModel = loadedViewModel() + viewModel.loadPhoto(photoPath) + advance() + assertEquals(AppError.NOT_FOUND, viewModel.uiState.value.photoLoadErrors[photoPath]) + viewModel.attachPhoto(galleryPhoto) + + uploaded() + viewModel.send() + runCurrent() + + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + } + + /** Delegates to [FakeChatRepository] and records each photo download, by path, in [loads]. */ + private class CountingDownloads(private val fake: FakeChatRepository) : ChatRepository by fake { + val loads = mutableListOf() + + override suspend fun loadMessagePhoto(imagePath: String): ByteArray { + loads += imagePath + return fake.loadMessagePhoto(imagePath) + } + } + /** * Creates photos like the camera folder: "taken_0", "taken_1", … in [taken], or none while * [full]. Records the photos deleted. From bd403670f5087ed5bb47dc49bb178da0b4ca1820 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:12:11 +0100 Subject: [PATCH 06/16] fix(chat): tag a photo that failed to download Two test tags on one node keep only the first, so the error placeholder was tagged messagePhoto and photoLoadError was never found. Each state now gets a single tag. Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 21 +++++++------------ 1 file changed, 7 insertions(+), 14 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 d6bfe4c9..7b5bf791 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 @@ -742,12 +742,13 @@ private fun BubblePhoto(messageId: String, photo: MessagePhoto) { } val description = stringResource(R.string.conversation_photo) val shape = RoundedCornerShape(10.dp) - val modifier = - Modifier.fillMaxWidth() - .height(BubblePhotoHeight) - .clip(shape) - .testTag(ConversationScreenTags.messagePhoto(messageId)) val current = decoded + val downloadFailed = photo.failed && current !is DecodedPhoto.Shown + // One tag per state: of two test tags on a node, only the first counts. + val tag = + if (downloadFailed) ConversationScreenTags.photoLoadError(messageId) + else ConversationScreenTags.messagePhoto(messageId) + val modifier = Modifier.fillMaxWidth().height(BubblePhotoHeight).clip(shape).testTag(tag) when { current is DecodedPhoto.Shown -> Image( @@ -758,15 +759,7 @@ private fun BubblePhoto(messageId: String, photo: MessagePhoto) { ) // Undecodable bytes would fail again, so only a failed download offers to retry. photo.failed || current is DecodedPhoto.Failed -> - PhotoLoadError( - onRetry = photo.load.takeIf { photo.failed }, - modifier = - modifier.then( - if (photo.failed) - Modifier.testTag(ConversationScreenTags.photoLoadError(messageId)) - else Modifier - ), - ) + PhotoLoadError(onRetry = photo.load.takeIf { photo.failed }, modifier = modifier) else -> Box( modifier = From 3c637bd73afc325ef6a3731ed987061b5bfd3a35 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:49:44 +0100 Subject: [PATCH 07/16] test(chat): cover the photos of the messages Co-Authored-By: Claude Opus 5.5 --- .../chat/ui/ConversationScreenTest.kt | 117 +++++++++++++++++- 1 file changed, 116 insertions(+), 1 deletion(-) 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 62dfbec5..b31a9149 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 @@ -23,6 +23,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.assertHeightIsEqualTo import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotDisplayed @@ -33,6 +34,7 @@ import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasTestTag +import androidx.compose.ui.test.hasText import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText @@ -134,6 +136,7 @@ class ConversationScreenTest { onTakePhoto: () -> Unit = {}, onChoosePhoto: () -> Unit = {}, onRemoveAttachedPhoto: () -> Unit = {}, + onLoadPhoto: (String) -> Unit = {}, onRetryPhoto: (String) -> Unit = {}, onDiscardPhoto: (String) -> Unit = {}, ) { @@ -148,6 +151,7 @@ class ConversationScreenTest { onTakePhoto = onTakePhoto, onChoosePhoto = onChoosePhoto, onRemoveAttachedPhoto = onRemoveAttachedPhoto, + onLoadPhoto = onLoadPhoto, onRetryPhoto = onRetryPhoto, onDiscardPhoto = onDiscardPhoto, zone = ZoneOffset.UTC, @@ -1004,7 +1008,7 @@ class ConversationScreenTest { assertEquals(1, sends) } - // Photos being sent + // Photo bubbles private val photoTime = Instant.parse("2026-11-11T09:16:00Z") @@ -1012,9 +1016,120 @@ class ConversationScreenTest { private fun photoMessage(id: String, senderUid: String, caption: String = "") = ChatMessage(id, senderUid, caption, photoTime, imagePath = "conversations/drill_renter/$id") + private val myPhoto = photoMessage("m3", "renter", caption = "Here it is") + private val theirPhoto = photoMessage("m4", james.uid) + private fun pending(status: PendingPhotoStatus, error: AppError? = null) = PendingPhoto("m5", galleryPhoto, "And the shelf", status, error) + /** Waits until the photo of message [id] is drawn: [redPhoto] decoded, not the placeholder. */ + private fun waitForRedPhoto(id: String) { + composeTestRule.waitUntil(5_000) { + val image = + composeTestRule + .onNodeWithTag(ConversationScreenTags.messagePhoto(id), useUnmergedTree = true) + .captureToImage() + image.toPixelMap()[image.width / 2, image.height / 2] == Color.Red + } + } + + private fun photoNode(id: String) = + composeTestRule.onNodeWithTag(ConversationScreenTags.messagePhoto(id), useUnmergedTree = true) + + @Test + fun myPhotoWithACaption_isOneTalkBackItem_photoThenCaptionThenFooter() { + setContent(loaded.copy(messages = listOf(myPhoto))) + + node(ConversationScreenTags.myMessage("m3")) + .assertContentDescriptionEquals(string(R.string.conversation_photo)) + .assertTextEquals("Here it is", "You · 09:16") + val photo = photoNode("m3").getBoundsInRoot() + val caption = text("Here it is").getBoundsInRoot() + assertTrue(photo.bottom <= caption.top) + } + + @Test + fun theirPhotoWithoutACaption_showsOnlyThePhotoAndTheFooter() { + setContent(loaded.copy(messages = listOf(theirPhoto))) + + node(ConversationScreenTags.theirMessage("m4")) + .assertContentDescriptionEquals(string(R.string.conversation_photo)) + .assertTextEquals("james · 09:16") + photoNode("m4").assertIsDisplayed() + } + + @Test + fun photoNotDownloaded_isAskedForOnce_withAFixedSizePlaceholder() { + val loads = mutableListOf() + setContent(loaded.copy(messages = listOf(myPhoto, theirPhoto)), onLoadPhoto = { loads += it }) + + composeTestRule.waitForIdle() + assertEquals(listOf(theirPhoto.imagePath, myPhoto.imagePath), loads) + photoNode("m3").assertHeightIsEqualTo(200.dp) + node(ConversationScreenTags.photoLoadError("m3")).assertDoesNotExist() + } + + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) // Real decoding and drawing. + fun downloadedPhoto_isShownAtTheSameSize_withoutAskingAgain() { + val loads = mutableListOf() + setContent( + loaded.copy( + messages = listOf(theirPhoto), + messagePhotos = mapOf(theirPhoto.imagePath!! to redPhoto()), + ), + onLoadPhoto = { loads += it }, + ) + + waitForRedPhoto("m4") + photoNode("m4").assertHeightIsEqualTo(200.dp) + assertEquals(emptyList(), loads) + } + + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) // The legacy BitmapFactory "decodes" any bytes. + fun undecodablePhoto_saysItCouldNotLoad_withoutOfferingARetry() { + setContent( + loaded.copy( + messages = listOf(theirPhoto), + messagePhotos = mapOf(theirPhoto.imagePath!! to byteArrayOf(1, 2, 3)), + ) + ) + + composeTestRule.waitUntil(5_000) { + composeTestRule + .onAllNodes( + hasText(string(R.string.conversation_photo_load_failed)), + useUnmergedTree = true, + ) + .fetchSemanticsNodes() + .isNotEmpty() + } + node(ConversationScreenTags.photoLoadError("m4")).assertDoesNotExist() + } + + @Test + fun photoThatFailedToDownload_offersARetry_andTappingAsksForItAgain() { + val loads = mutableListOf() + setContent( + loaded.copy( + messages = listOf(theirPhoto), + photoLoadErrors = mapOf(theirPhoto.imagePath!! to AppError.NETWORK), + ), + onLoadPhoto = { loads += it }, + ) + composeTestRule.waitForIdle() + assertEquals(emptyList(), loads) + + composeTestRule + .onNodeWithTag(ConversationScreenTags.photoLoadError("m4"), useUnmergedTree = true) + .assertHeightIsEqualTo(200.dp) + .performClick() + + text(string(R.string.conversation_photo_load_failed_retry)).assertIsDisplayed() + assertEquals(listOf(theirPhoto.imagePath), loads) + } + @Test fun pendingPhoto_whoseMessageArrived_showsOnce() { setContent( From ebba9c8388067a3dc6410e6d8a4e2aa330b22654 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:14:57 +0100 Subject: [PATCH 08/16] test(chat): cover the photo preview in the inbox Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/InboxScreenTest.kt | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt index cbfea4d4..767fcccb 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt @@ -233,6 +233,38 @@ class InboxScreenTest { .assertTextEquals(context.getString(R.string.inbox_last_message_mine, "See you at 6")) } + @Test + fun rowPreview_ofAPhotoAlone_saysPhoto() { + val photo = context.getString(R.string.inbox_last_message_photo) + val drill = conversation("drill").copy(lastMessageText = "") + setContent(loaded(row(drill))) + + node(InboxScreenTags.preview(drill.id)).assertTextEquals(photo) + // Read once in the row: the icon next to it is decorative. + rowOf(drill).assert(hasText(photo)) + composeTestRule + .onAllNodes( + hasContentDescription(photo) and + hasAnyAncestor(hasTestTag(InboxScreenTags.row(drill.id))), + useUnmergedTree = true, + ) + .assertCountEquals(0) + } + + @Test + fun rowPreview_ofMyOwnPhoto_startsWithYou() { + val drill = conversation("drill").copy(lastMessageText = "") + setContent(loaded(row(drill, isLastMessageMine = true))) + + node(InboxScreenTags.preview(drill.id)) + .assertTextEquals( + context.getString( + R.string.inbox_last_message_mine, + context.getString(R.string.inbox_last_message_photo), + ) + ) + } + @Test fun rowWithoutLastMessageText_showsNoPreview() { val drill = conversation("drill") From 46b687a49a7a44649e06ef0b1c11e0c5cf6f2f19 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:48:42 +0100 Subject: [PATCH 09/16] fix(chat): wait for a pending photo instead of retrying its download Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 23 ++++-- .../chat/viewmodel/ConversationViewModel.kt | 56 ++------------ .../viewmodel/ConversationViewModelTest.kt | 77 ------------------- 3 files changed, 25 insertions(+), 131 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 7b5bf791..aea6325d 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 @@ -250,7 +250,8 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { * @param onChoosePhoto called when the user picks "Choose from gallery" in the photo menu. * @param onRemoveAttachedPhoto called when the user taps ✕ on the attached photo. * @param onLoadPhoto called with a message's imagePath when its bubble shows and the photo is - * neither downloaded nor failed, and when the user taps a photo that failed to load. + * neither pending, downloaded nor failed, when a pending photo is marked uploaded, and when the + * user taps a photo that failed to load. * @param onRetryPhoto called with the message ID of a failed photo when the user taps Retry. * @param onDiscardPhoto called with the message ID of a failed photo when the user taps Remove. * @param zone time zone of the message times. @@ -575,6 +576,7 @@ private fun MessageList( MessagePhoto( bytes = uiState.messagePhotos[path], failed = path in uiState.photoLoadErrors, + pending = message.photoPending, load = { photoActions.load(path) }, ) }, @@ -617,9 +619,15 @@ private fun LoadErrorRow(text: String, onRetry: () -> Unit) { /** * The photo of a message: its downloaded [bytes], or null until they arrive; [failed] when the - * download failed. [load] asks for it. + * download failed; [pending] while its sender is still uploading it, so it can't be downloaded yet. + * [load] asks for it. */ -private class MessagePhoto(val bytes: ByteArray?, val failed: Boolean, val load: () -> Unit) +private class MessagePhoto( + val bytes: ByteArray?, + val failed: Boolean, + val pending: Boolean, + val load: () -> Unit, +) /** * One message: the user's own at the end of the row, the other participant's at the start. A photo @@ -723,13 +731,16 @@ private sealed interface DecodedPhoto { } /** - * The photo of a message, asked for when the bubble first shows: a placeholder of the same size - * while it downloads and decodes, and one that offers to try again when it could not be loaded. + * The photo of a message, asked for when the bubble first shows, or once its sender has uploaded + * it: a placeholder of the same size while it uploads, downloads and decodes, and one that offers + * to try again when it could not be loaded. */ @Composable private fun BubblePhoto(messageId: String, photo: MessagePhoto) { // Not asked again on its own after a failure: only when the user taps to retry. - LaunchedEffect(messageId) { if (photo.bytes == null && !photo.failed) photo.load() } + LaunchedEffect(messageId, photo.pending) { + if (!photo.pending && photo.bytes == null && !photo.failed) photo.load() + } val decoded by produceState(initialValue = DecodedPhoto.Loading, photo.bytes) { val bytes = photo.bytes diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt index a0b7a0ca..5b6e0341 100644 --- a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt @@ -20,26 +20,15 @@ import com.android.polybazaar.listing.model.PhotoStorage import com.android.polybazaar.profile.model.ProfileRepository import java.time.Instant import java.util.concurrent.atomic.AtomicBoolean -import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch -import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -import kotlinx.coroutines.withTimeoutOrNull - -/** - * How long to wait before each new try at a message photo that is not in Storage yet: a photo's - * message reaches the conversation before the photo, which may still be uploading. About 30 s in - * all, as long as a send may take before it gives up. - */ -private val PhotoUploadWaits = listOf(1, 2, 4, 8, 15).map { it.seconds } /** What the listing a conversation is about has become. */ enum class ConversationListingStatus { @@ -202,8 +191,6 @@ class ConversationViewModel( private val takenPhotos = mutableSetOf() // The message photos being downloaded, so that no photo is downloaded twice at once. private val photosDownloading = mutableSetOf() - // The paths of the photos this device just finished sending, to stop waiting for them at once. - private val sentPhotoPaths = MutableSharedFlow(extraBufferCapacity = 8) init { observeListing() @@ -369,7 +356,6 @@ class ConversationViewModel( } // Sent: nothing can fail any more, so the taken photo is no longer needed. deleteIfTaken(pending.photo) - showSentPhoto(pending.messageId) } catch (exception: Exception) { if (exception is CancellationException) throw exception // A refusal from a pause or deletion of the listing also reaches its observation, which @@ -411,16 +397,19 @@ class ConversationViewModel( /** * Downloads the photo of a message at [path], its [ChatMessage.imagePath], unless it is already - * downloaded or downloading. A message's photo never changes, so it is downloaded once. A photo - * not in Storage yet is still loading, not failed: it is tried again for a while, since it may - * still be uploading. After a failure, calling it again clears the error and tries again. + * downloaded or downloading. A message's photo never changes, so it is downloaded once. Ignored + * while the message's photo is still pending ([ChatMessage.photoPending]): it is not in Storage + * yet, so call it again once the message says it is uploaded. After a failure, calling it again + * clears the error and tries again. */ fun loadPhoto(path: String) { - if (path in _uiState.value.messagePhotos || !photosDownloading.add(path)) return + val state = _uiState.value + if (state.messages.any { it.imagePath == path && it.photoPending }) return + if (path in state.messagePhotos || !photosDownloading.add(path)) return _uiState.update { it.copy(photoLoadErrors = it.photoLoadErrors - path) } viewModelScope.launch { try { - val photo = downloadOnceUploaded(path) + val photo = chatRepository.loadMessagePhoto(path) _uiState.update { it.copy(messagePhotos = it.messagePhotos + (path to photo)) } } catch (exception: Exception) { if (exception is CancellationException) throw exception @@ -432,35 +421,6 @@ class ConversationViewModel( } } - /** - * Downloads the photo at [path]. While Storage answers NOT_FOUND, waits [PhotoUploadWaits] in - * turn and tries again, or at once when this device finishes sending that photo. Any other - * failure, or a photo still missing after the last wait, is thrown. - */ - private suspend fun downloadOnceUploaded(path: String): ByteArray { - for (wait in PhotoUploadWaits) { - try { - return chatRepository.loadMessagePhoto(path) - } catch (exception: Exception) { - if (exception is CancellationException || exception.toAppError() != AppError.NOT_FOUND) { - throw exception - } - } - withTimeoutOrNull(wait) { sentPhotoPaths.first { it == path } } - } - return chatRepository.loadMessagePhoto(path) - } - - /** - * Shows the photo of the message [messageId] this device just sent, now in Storage: a download - * waiting for it tries again at once, and one that already gave up starts again. - */ - private fun showSentPhoto(messageId: String) { - val state = _uiState.value - val path = state.messages.firstOrNull { it.id == messageId }?.imagePath ?: return - if (path in state.photoLoadErrors) loadPhoto(path) else sentPhotoPaths.tryEmit(path) - } - fun dismissSendError() { _uiState.update { it.copy(sendError = null) } } diff --git a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt index be02f0e2..90748603 100644 --- a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt @@ -25,7 +25,6 @@ import com.android.polybazaar.profile.model.FakeProfileRepository import com.google.firebase.firestore.FirebaseFirestoreException import java.net.UnknownHostException import java.time.Instant -import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -1768,11 +1767,6 @@ class ConversationViewModelTest { /** Runs what is due now without moving the virtual clock. */ private fun runCurrent() = testDispatcher.scheduler.runCurrent() - private fun advanceBy(millis: Long) { - testDispatcher.scheduler.advanceTimeBy(millis) - runCurrent() - } - /** The photo is in Storage now. */ private fun uploaded() { chat.photoLoadFailure = null @@ -1843,77 +1837,6 @@ class ConversationViewModelTest { assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) } - @Test - fun loadPhoto_notFoundYet_staysLoading_andArrivesOnALaterTry() { - chat.photoLoadFailure = missing - val viewModel = inConversation() - viewModel.loadPhoto(photoPath) - runCurrent() - assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) - assertEquals(emptyMap(), viewModel.uiState.value.messagePhotos) - - uploaded() - advanceBy(999) - assertEquals(1, downloads.loads.size) - advanceBy(1) - - assertEquals(2, downloads.loads.size) - assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) - } - - @Test - fun loadPhoto_stillNotFound_recordsTheErrorOnlyAfterTheLastWait() { - chat.photoLoadFailure = missing - val viewModel = inConversation() - viewModel.loadPhoto(photoPath) - runCurrent() - - // 1 + 2 + 4 + 8 + 15 s. - val allWaits = 30.seconds.inWholeMilliseconds - advanceBy(allWaits - 1) - assertEquals(5, downloads.loads.size) - assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) - advanceBy(1) - - assertEquals(6, downloads.loads.size) - assertEquals(mapOf(photoPath to AppError.NOT_FOUND), viewModel.uiState.value.photoLoadErrors) - } - - @Test - fun myPhotoSent_wakesADownloadWaitingForIt() { - givenConversation(messages = arrayOf(photoMessage)) - chat.photoLoadFailure = missing - val viewModel = loadedViewModel() - viewModel.loadPhoto(photoPath) - runCurrent() - viewModel.attachPhoto(galleryPhoto) - - uploaded() - viewModel.send() - runCurrent() - - assertEquals(2, downloads.loads.size) - assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) - } - - @Test - fun myPhotoSent_restartsADownloadThatGaveUp() { - givenConversation(messages = arrayOf(photoMessage)) - chat.photoLoadFailure = missing - val viewModel = loadedViewModel() - viewModel.loadPhoto(photoPath) - advance() - assertEquals(AppError.NOT_FOUND, viewModel.uiState.value.photoLoadErrors[photoPath]) - viewModel.attachPhoto(galleryPhoto) - - uploaded() - viewModel.send() - runCurrent() - - assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) - assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) - } - /** Delegates to [FakeChatRepository] and records each photo download, by path, in [loads]. */ private class CountingDownloads(private val fake: FakeChatRepository) : ChatRepository by fake { val loads = mutableListOf() From 231195650558c459a34d2738ce263b08bd429c89 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:48:42 +0100 Subject: [PATCH 10/16] test(chat): cover photos that are still pending Co-Authored-By: Claude Opus 5.5 --- .../chat/ui/ConversationScreenTest.kt | 28 ++++++++++++ .../viewmodel/ConversationViewModelTest.kt | 44 +++++++++++++++++++ 2 files changed, 72 insertions(+) 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 b31a9149..3a7c0de8 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 @@ -1069,6 +1069,34 @@ class ConversationScreenTest { node(ConversationScreenTags.photoLoadError("m3")).assertDoesNotExist() } + @Test + fun pendingPhoto_showsTheLoadingPlaceholder_withoutBeingAskedFor() { + val loads = mutableListOf() + val uploading = theirPhoto.copy(photoPending = true) + setContent(loaded.copy(messages = listOf(uploading)), onLoadPhoto = { loads += it }) + + composeTestRule.waitForIdle() + assertEquals(emptyList(), loads) + photoNode("m4").assertHeightIsEqualTo(200.dp) + node(ConversationScreenTags.photoLoadError("m4")).assertDoesNotExist() + } + + @Test + fun pendingPhoto_isAskedForOnceMarkedUploaded() { + val loads = mutableListOf() + var state by + mutableStateOf(loaded.copy(messages = listOf(theirPhoto.copy(photoPending = true)))) + composeTestRule.setContent { + ConversationContent(uiState = state, onLoadPhoto = { loads += it }, zone = ZoneOffset.UTC) + } + composeTestRule.waitForIdle() + + state = state.copy(messages = listOf(theirPhoto)) + composeTestRule.waitForIdle() + + assertEquals(listOf(theirPhoto.imagePath), loads) + } + @Test @GraphicsMode(GraphicsMode.Mode.NATIVE) // Real decoding and drawing. fun downloadedPhoto_isShownAtTheSameSize_withoutAskingAgain() { diff --git a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt index 90748603..d8633a40 100644 --- a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt @@ -1837,6 +1837,50 @@ class ConversationViewModelTest { assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) } + @Test + fun loadPhoto_notFound_recordsTheErrorAtOnce() { + // Not pending, so it was uploaded: a missing photo will not arrive later. + chat.photoLoadFailure = missing + val viewModel = inConversation() + + viewModel.loadPhoto(photoPath) + runCurrent() + + assertEquals(mapOf(photoPath to AppError.NOT_FOUND), viewModel.uiState.value.photoLoadErrors) + assertEquals(1, downloads.loads.size) + } + + @Test + fun loadPhoto_whileThePhotoIsPending_downloadsNothing() { + givenConversation(messages = arrayOf(photoMessage.copy(photoPending = true))) + uploaded() + val viewModel = loadedViewModel() + + viewModel.loadPhoto(photoPath) + advance() + + assertEquals(emptyList(), downloads.loads) + assertEquals(emptyMap(), viewModel.uiState.value.messagePhotos) + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + } + + @Test + fun loadPhoto_onceThePhotoIsMarkedUploaded_downloadsIt() { + givenConversation(messages = arrayOf(photoMessage.copy(photoPending = true))) + uploaded() + val viewModel = loadedViewModel() + viewModel.loadPhoto(photoPath) + advance() + + chat.messages.value = mapOf(conversation.id to listOf(photoMessage)) + advance() + viewModel.loadPhoto(photoPath) + advance() + + assertEquals(listOf(photoPath), downloads.loads) + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + } + /** Delegates to [FakeChatRepository] and records each photo download, by path, in [loads]. */ private class CountingDownloads(private val fake: FakeChatRepository) : ChatRepository by fake { val loads = mutableListOf() From 59ac533f9bd12bd6bbf974c2fa430dccb433ce3a Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 21:29:24 +0100 Subject: [PATCH 11/16] test(chat): cover the photos preview of the conversation Co-Authored-By: Claude Opus 5.5 --- .../android/polybazaar/chat/ui/ConversationScreen.kt | 2 +- .../polybazaar/chat/ui/ConversationScreenTest.kt | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) 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 aea6325d..167cda54 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 @@ -1259,7 +1259,7 @@ internal fun ConversationPhotosPreview() { listOf( PendingPhoto( messageId = "3", - photo = Uri.parse("content://media/photo/3"), + photo = Uri.parse("file:///preview/photo_3.jpg"), caption = "And the shelf I mean", status = PendingPhotoStatus.FAILED, error = AppError.NETWORK, 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 3a7c0de8..1cb0d246 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 @@ -747,6 +747,17 @@ class ConversationScreenTest { node(ConversationScreenTags.theirMessage("2")).assertIsDisplayed() } + @Test + fun photosPreview_showsTheirPhotoLoadingAndMyFailedPhoto() { + composeTestRule.setContent { ConversationPhotosPreview() } + + composeTestRule + .onNodeWithTag(ConversationScreenTags.messagePhoto("2"), useUnmergedTree = true) + .assertExists() + node(ConversationScreenTags.pendingPhoto("3")).assertExists() + node(ConversationScreenTags.retryPhoto("3")).assertExists() + } + @Test fun conversationBody_prefersTheMessages_thenTheError_thenLoading_elseEmpty() { fun body(messages: Boolean, error: Boolean, loading: Boolean) = From e3de7bf100f8f98bba16f141842846b95c2e8e7e Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 21:53:21 +0100 Subject: [PATCH 12/16] fix(chat): decode message photos once, above the list Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 52 +++++++++++++------ .../chat/ui/ConversationScreenTest.kt | 27 ++++++++++ 2 files changed, 62 insertions(+), 17 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 167cda54..7c1d8e0c 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 @@ -44,6 +44,8 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember @@ -541,6 +543,8 @@ private fun MessageList( val messages = uiState.shownMessages val pendingPhotos = uiState.pendingPhotos val listState = rememberLazyListState() + // Decoded above the list: a bubble that scrolls out of view and back shows its photo at once. + val decodedPhotos = rememberDecodedPhotos(uiState.messagePhotos) // The list keeps its place by key, so a new message or photo would arrive below the view without // this. LaunchedEffect(messages.lastOrNull()?.id, pendingPhotos.lastOrNull()?.messageId) { @@ -574,7 +578,8 @@ private fun MessageList( photo = message.imagePath?.let { path -> MessagePhoto( - bytes = uiState.messagePhotos[path], + downloaded = path in uiState.messagePhotos, + decoded = decodedPhotos[path] ?: DecodedPhoto.Loading, failed = path in uiState.photoLoadErrors, pending = message.photoPending, load = { photoActions.load(path) }, @@ -618,12 +623,13 @@ private fun LoadErrorRow(text: String, onRetry: () -> Unit) { } /** - * The photo of a message: its downloaded [bytes], or null until they arrive; [failed] when the - * download failed; [pending] while its sender is still uploading it, so it can't be downloaded yet. - * [load] asks for it. + * The photo of a message: [downloaded] once its bytes arrived, [decoded] from them above the list + * ([DecodedPhoto.Loading] until then); [failed] when the download failed; [pending] while its + * sender is still uploading it, so it can't be downloaded yet. [load] asks for it. */ private class MessagePhoto( - val bytes: ByteArray?, + val downloaded: Boolean, + val decoded: DecodedPhoto, val failed: Boolean, val pending: Boolean, val load: () -> Unit, @@ -721,6 +727,28 @@ private fun ColumnScope.BubbleFooter(text: String) { ) } +/** + * [photos] decoded off the main thread, by path: each one once, and again only if its bytes change. + * A photo still decoding is absent. + */ +@Composable +private fun rememberDecodedPhotos(photos: Map): Map { + val decoded = remember { mutableStateMapOf() } + photos.forEach { (path, bytes) -> + // One effect per photo: a photo that finishes downloading starts its own decode, without + // restarting the ones already running. + key(path) { + LaunchedEffect(bytes) { + decoded[path] = + decodePhotoPreview(bytes, maxSize = BUBBLE_PHOTO_MAX_SIZE)?.let { + DecodedPhoto.Shown(it) + } ?: DecodedPhoto.Failed + } + } + } + return decoded +} + /** A message photo after it is decoded, or why it is not shown. */ private sealed interface DecodedPhoto { data object Loading : DecodedPhoto @@ -739,21 +767,11 @@ private sealed interface DecodedPhoto { private fun BubblePhoto(messageId: String, photo: MessagePhoto) { // Not asked again on its own after a failure: only when the user taps to retry. LaunchedEffect(messageId, photo.pending) { - if (!photo.pending && photo.bytes == null && !photo.failed) photo.load() + if (!photo.pending && !photo.downloaded && !photo.failed) photo.load() } - val decoded by - produceState(initialValue = DecodedPhoto.Loading, photo.bytes) { - val bytes = photo.bytes - value = - if (bytes == null) DecodedPhoto.Loading - else - decodePhotoPreview(bytes, maxSize = BUBBLE_PHOTO_MAX_SIZE)?.let { - DecodedPhoto.Shown(it) - } ?: DecodedPhoto.Failed - } val description = stringResource(R.string.conversation_photo) val shape = RoundedCornerShape(10.dp) - val current = decoded + val current = photo.decoded val downloadFailed = photo.failed && current !is DecodedPhoto.Shown // One tag per state: of two test tags on a node, only the first counts. val tag = 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 1cb0d246..f836a181 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 @@ -1125,6 +1125,33 @@ class ConversationScreenTest { assertEquals(emptyList(), loads) } + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) // Real decoding and drawing. + fun decodedPhoto_scrolledOutOfViewAndBack_isShownAtOnce() { + val later = + List(30) { ChatMessage("t$it", "renter", "Message $it", photoTime.plusSeconds(60L + it)) } + setContent( + loaded.copy( + messages = listOf(theirPhoto) + later, + messagePhotos = mapOf(theirPhoto.imagePath!! to redPhoto()), + ) + ) + val list = node(ConversationScreenTags.MESSAGE_LIST) + // Newest first: the photo is last. + list.performScrollToIndex(later.size) + waitForRedPhoto("m4") + + list.performScrollToIndex(0) + photoNode("m4").assertDoesNotExist() + // Frozen clock: a photo decoded again would still show the placeholder. + composeTestRule.mainClock.autoAdvance = false + list.performScrollToIndex(later.size) + + // Not decoded again: drawn in the first frame, without the placeholder. + val image = photoNode("m4").captureToImage() + assertEquals(Color.Red, image.toPixelMap()[image.width / 2, image.height / 2]) + } + @Test @GraphicsMode(GraphicsMode.Mode.NATIVE) // The legacy BitmapFactory "decodes" any bytes. fun undecodablePhoto_saysItCouldNotLoad_withoutOfferingARetry() { From e14b662169afe8e07f981e6e8c5cd4868d18243f Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 21:55:14 +0100 Subject: [PATCH 13/16] fix(chat): offer no retry for a photo missing or refused Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 28 ++++++++++++------- .../chat/ui/ConversationScreenTest.kt | 28 +++++++++++++++++++ 2 files changed, 46 insertions(+), 10 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 7c1d8e0c..ed996da9 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 @@ -183,6 +183,9 @@ private val BubblePhotoHeight = 200.dp /** Longest side, in pixels, a message photo is decoded at: sharp across a bubble. */ private const val BUBBLE_PHOTO_MAX_SIZE = 1024 +/** Download errors a retry can't fix: the photo is gone, or the rules refuse it. */ +private val PermanentPhotoErrors = setOf(AppError.NOT_FOUND, AppError.PERMISSION_DENIED) + private val TimeFormat = DateTimeFormatter.ofPattern("HH:mm") /** @@ -580,7 +583,7 @@ private fun MessageList( MessagePhoto( downloaded = path in uiState.messagePhotos, decoded = decodedPhotos[path] ?: DecodedPhoto.Loading, - failed = path in uiState.photoLoadErrors, + loadError = uiState.photoLoadErrors[path], pending = message.photoPending, load = { photoActions.load(path) }, ) @@ -624,13 +627,13 @@ private fun LoadErrorRow(text: String, onRetry: () -> Unit) { /** * The photo of a message: [downloaded] once its bytes arrived, [decoded] from them above the list - * ([DecodedPhoto.Loading] until then); [failed] when the download failed; [pending] while its + * ([DecodedPhoto.Loading] until then); [loadError] why the download failed; [pending] while its * sender is still uploading it, so it can't be downloaded yet. [load] asks for it. */ private class MessagePhoto( val downloaded: Boolean, val decoded: DecodedPhoto, - val failed: Boolean, + val loadError: AppError?, val pending: Boolean, val load: () -> Unit, ) @@ -760,19 +763,20 @@ private sealed interface DecodedPhoto { /** * The photo of a message, asked for when the bubble first shows, or once its sender has uploaded - * it: a placeholder of the same size while it uploads, downloads and decodes, and one that offers - * to try again when it could not be loaded. + * it: a placeholder of the same size while it uploads, downloads and decodes, and one that says it + * could not be loaded, offering to try again when that may help. */ @Composable private fun BubblePhoto(messageId: String, photo: MessagePhoto) { // Not asked again on its own after a failure: only when the user taps to retry. LaunchedEffect(messageId, photo.pending) { - if (!photo.pending && !photo.downloaded && !photo.failed) photo.load() + if (!photo.pending && !photo.downloaded && photo.loadError == null) photo.load() } val description = stringResource(R.string.conversation_photo) val shape = RoundedCornerShape(10.dp) val current = photo.decoded - val downloadFailed = photo.failed && current !is DecodedPhoto.Shown + val loadError = photo.loadError + val downloadFailed = loadError != null && current !is DecodedPhoto.Shown // One tag per state: of two test tags on a node, only the first counts. val tag = if (downloadFailed) ConversationScreenTags.photoLoadError(messageId) @@ -786,9 +790,13 @@ private fun BubblePhoto(messageId: String, photo: MessagePhoto) { contentScale = ContentScale.Crop, modifier = modifier, ) - // Undecodable bytes would fail again, so only a failed download offers to retry. - photo.failed || current is DecodedPhoto.Failed -> - PhotoLoadError(onRetry = photo.load.takeIf { photo.failed }, modifier = modifier) + // Undecodable bytes, or a photo missing or refused, would fail again: only another failed + // download offers to retry. + loadError != null || current is DecodedPhoto.Failed -> + PhotoLoadError( + onRetry = photo.load.takeIf { loadError != null && loadError !in PermanentPhotoErrors }, + modifier = modifier, + ) else -> Box( modifier = 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 f836a181..0adf9b9b 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 @@ -23,6 +23,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.assertHasNoClickAction import androidx.compose.ui.test.assertHeightIsEqualTo import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsEnabled @@ -1196,6 +1197,33 @@ class ConversationScreenTest { assertEquals(listOf(theirPhoto.imagePath), loads) } + @Test + fun photoMissingOrRefused_saysItCouldNotLoad_withoutOfferingARetry() { + val loads = mutableListOf() + var error by mutableStateOf(AppError.NOT_FOUND) + composeTestRule.setContent { + ConversationContent( + uiState = + loaded.copy( + messages = listOf(theirPhoto), + photoLoadErrors = mapOf(theirPhoto.imagePath!! to error), + ), + zone = ZoneOffset.UTC, + onLoadPhoto = { loads += it }, + ) + } + + for (permanent in listOf(AppError.NOT_FOUND, AppError.PERMISSION_DENIED)) { + error = permanent + composeTestRule + .onNodeWithTag(ConversationScreenTags.photoLoadError("m4"), useUnmergedTree = true) + .assertHasNoClickAction() + text(string(R.string.conversation_photo_load_failed)).assertIsDisplayed() + text(string(R.string.conversation_photo_load_failed_retry)).assertDoesNotExist() + } + assertEquals(emptyList(), loads) + } + @Test fun pendingPhoto_whoseMessageArrived_showsOnce() { setContent( From ee52f7f5df7dd3f4b7cee112262b26ddcdd88bd7 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 22:01:04 +0100 Subject: [PATCH 14/16] fix(chat): announce the photo retry as a button Co-Authored-By: Claude Opus 5.5 --- .../android/polybazaar/chat/ui/ConversationScreen.kt | 11 ++++++++++- .../polybazaar/chat/ui/ConversationScreenTest.kt | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) 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 ed996da9..385c03c4 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 @@ -63,6 +63,7 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.liveRegion @@ -821,7 +822,15 @@ private fun PhotoLoadError(onRetry: (() -> Unit)?, modifier: Modifier) { modifier = modifier .background(AuthColors.Outline) - .then(if (onRetry != null) Modifier.clickable(onClick = onRetry) else Modifier) + .then( + if (onRetry != null) + Modifier.clickable( + role = Role.Button, + onClickLabel = stringResource(R.string.conversation_retry), + onClick = onRetry, + ) + else Modifier + ) .padding(12.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterVertically), 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 0adf9b9b..ea4cbadb 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 @@ -17,6 +17,8 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toPixelMap import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.SemanticsNodeInteraction @@ -1191,6 +1193,13 @@ class ConversationScreenTest { composeTestRule .onNodeWithTag(ConversationScreenTags.photoLoadError("m4"), useUnmergedTree = true) .assertHeightIsEqualTo(200.dp) + // Announced by TalkBack as a button that retries. + .assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Button)) + .assert( + SemanticsMatcher("retries on click") { + it.config[SemanticsActions.OnClick].label == string(R.string.conversation_retry) + } + ) .performClick() text(string(R.string.conversation_photo_load_failed_retry)).assertIsDisplayed() From 5cb794ca1e18fa61be127c4b4efbaa44aaacdb0c Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 22:02:41 +0100 Subject: [PATCH 15/16] fix(chat): tell TalkBack a message photo is still loading Co-Authored-By: Claude Opus 5.5 --- .../com/android/polybazaar/chat/ui/ConversationScreen.kt | 4 +++- app/src/main/res/values/strings.xml | 1 + .../android/polybazaar/chat/ui/ConversationScreenTest.kt | 7 +++++-- 3 files changed, 9 insertions(+), 3 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 385c03c4..42f4159f 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 @@ -774,6 +774,8 @@ private fun BubblePhoto(messageId: String, photo: MessagePhoto) { if (!photo.pending && !photo.downloaded && photo.loadError == null) photo.load() } val description = stringResource(R.string.conversation_photo) + // Not the same as the photo's, so TalkBack users can tell it is not there yet. + val loadingDescription = stringResource(R.string.conversation_photo_loading) val shape = RoundedCornerShape(10.dp) val current = photo.decoded val loadError = photo.loadError @@ -802,7 +804,7 @@ private fun BubblePhoto(messageId: String, photo: MessagePhoto) { Box( modifier = modifier.background(AuthColors.Outline).semantics { - contentDescription = description + contentDescription = loadingDescription }, contentAlignment = Alignment.Center, ) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index bbf27199..15afa6c4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -99,6 +99,7 @@ Attached photo Remove photo Photo + Photo, loading Couldn’t load the photo · Tap to retry Couldn’t load the photo Sending… 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 ea4cbadb..415dafe6 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 @@ -1055,7 +1055,7 @@ class ConversationScreenTest { setContent(loaded.copy(messages = listOf(myPhoto))) node(ConversationScreenTags.myMessage("m3")) - .assertContentDescriptionEquals(string(R.string.conversation_photo)) + .assertContentDescriptionEquals(string(R.string.conversation_photo_loading)) .assertTextEquals("Here it is", "You · 09:16") val photo = photoNode("m3").getBoundsInRoot() val caption = text("Here it is").getBoundsInRoot() @@ -1067,7 +1067,7 @@ class ConversationScreenTest { setContent(loaded.copy(messages = listOf(theirPhoto))) node(ConversationScreenTags.theirMessage("m4")) - .assertContentDescriptionEquals(string(R.string.conversation_photo)) + .assertContentDescriptionEquals(string(R.string.conversation_photo_loading)) .assertTextEquals("james · 09:16") photoNode("m4").assertIsDisplayed() } @@ -1125,6 +1125,9 @@ class ConversationScreenTest { waitForRedPhoto("m4") photoNode("m4").assertHeightIsEqualTo(200.dp) + // Loaded: no longer "loading" for TalkBack. + node(ConversationScreenTags.theirMessage("m4")) + .assertContentDescriptionEquals(string(R.string.conversation_photo)) assertEquals(emptyList(), loads) } From 30a428e5733fbcaa3b65004752e127a307d6c949 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 22:03:49 +0100 Subject: [PATCH 16/16] test(chat): cover the inbox preview of a photo with a caption Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/InboxScreenTest.kt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt index 767fcccb..7105ff03 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt @@ -251,6 +251,22 @@ class InboxScreenTest { .assertCountEquals(0) } + @Test + fun rowPreview_ofAPhotoWithACaption_showsTheCaption_notPhoto() { + // A photo's caption is its message text, so it is the preview. + val drill = conversation("drill").copy(lastMessageText = "Both batteries are in") + setContent(loaded(row(drill))) + + node(InboxScreenTags.preview(drill.id)).assertTextEquals("Both batteries are in") + composeTestRule + .onAllNodes( + hasText(context.getString(R.string.inbox_last_message_photo)) and + hasAnyAncestor(hasTestTag(InboxScreenTags.row(drill.id))), + useUnmergedTree = true, + ) + .assertCountEquals(0) + } + @Test fun rowPreview_ofMyOwnPhoto_startsWithYou() { val drill = conversation("drill").copy(lastMessageText = "")