From 0940c384165618669c34bcdd8c85652f623dd42f Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Tue, 17 Nov 2026 21:06:27 +0100 Subject: [PATCH 1/3] refactor(chat): share the attempt helper between the chat ViewModels --- .../polybazaar/chat/viewmodel/Attempt.kt | 20 +++++++++++++++++++ .../chat/viewmodel/InboxViewModel.kt | 16 --------------- 2 files changed, 20 insertions(+), 16 deletions(-) create mode 100644 app/src/main/java/com/android/polybazaar/chat/viewmodel/Attempt.kt diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/Attempt.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/Attempt.kt new file mode 100644 index 00000000..c8a9184a --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/Attempt.kt @@ -0,0 +1,20 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.chat.viewmodel + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive + +/** + * Runs [block] and returns its result, or its failure. A [CancellationException] is rethrown only + * when the calling coroutine is itself cancelled, so cancelling a load still stops it. One thrown + * by a call that was cancelled on its own, such as a cancelled Firebase task, is returned as a + * failure like any other, so it cannot leave a screen loading forever. + */ +internal suspend fun attempt(block: suspend () -> T): Result = + try { + Result.success(block()) + } catch (exception: Exception) { + if (exception is CancellationException) currentCoroutineContext().ensureActive() + Result.failure(exception) + } diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/InboxViewModel.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/InboxViewModel.kt index 9728f9fc..a20969e9 100644 --- a/app/src/main/java/com/android/polybazaar/chat/viewmodel/InboxViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/InboxViewModel.kt @@ -17,8 +17,6 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -267,20 +265,6 @@ class InboxViewModel( } } -/** - * Runs [block] and returns its result, or its failure. A [CancellationException] is rethrown only - * when the calling coroutine is itself cancelled, so loading again still drops the old load. One - * thrown by a call that was cancelled on its own, such as a cancelled Firebase task, is returned as - * a failure like any other, so it cannot leave the inbox loading forever. - */ -private suspend fun attempt(block: suspend () -> T): Result = - try { - Result.success(block()) - } catch (exception: Exception) { - if (exception is CancellationException) currentCoroutineContext().ensureActive() - Result.failure(exception) - } - /** A listing as read for the inbox: [listing] is null when it could not be read. */ private data class ListingLookup(val listing: Listing?, val status: ListingStatus) From 4a4b0b18f0ac86311b85b3f8c4dba8ec02b97a69 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Tue, 17 Nov 2026 21:12:05 +0100 Subject: [PATCH 2/3] feat(chat): expose the listing, the role and both photos to the conversation screen --- .../chat/viewmodel/ConversationViewModel.kt | 60 ++++++++++++++++++- .../viewmodel/ConversationViewModelTest.kt | 2 +- 2 files changed, 59 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 56bc3770..33a388b5 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 @@ -43,8 +43,16 @@ enum class ConversationListingStatus { * conversation. Null until either is known. * @property listingStatus the state of the listing, kept up to date while the screen is open, or * null until it is known. + * @property listing the listing as last observed. Kept after it is deleted, and null when it was + * never read. + * @property listingPhoto the listing's first photo, or null while it is missing, downloading or + * failed to download. + * @property isRenter whether the signed-in user is the renter, so the other participant is the + * lender. * @property otherUser profile of the other participant, or null while it loads, after a failure, or * when they have no profile. + * @property otherUserPhoto the other participant's profile photo, or null while it is missing, + * downloading or failed to download. * @property draft the message being typed. * @property canSend whether the draft can be sent now. * @property firstMessageBlockedByPause true when the renter has no conversation yet and the listing @@ -62,7 +70,11 @@ data class ConversationUiState( val conversation: Conversation? = null, val listingTitle: String? = null, val listingStatus: ConversationListingStatus? = null, + val listing: Listing? = null, + val listingPhoto: ByteArray? = null, + val isRenter: Boolean = false, val otherUser: User? = null, + val otherUserPhoto: ByteArray? = null, val draft: String = "", val canSend: Boolean = false, val firstMessageBlockedByPause: Boolean = false, @@ -93,7 +105,8 @@ class ConversationViewModel( private val listingRepository: ListingRepository, ) : ViewModel() { - private val _uiState = MutableStateFlow(ConversationUiState(myUid = myUid)) + private val _uiState = + MutableStateFlow(ConversationUiState(myUid = myUid, isRenter = myUid == renterUid)) val uiState: StateFlow = _uiState.asStateFlow() // Read by derived(), which a write failure can run from a Firestore background thread. @@ -113,6 +126,14 @@ class ConversationViewModel( private var sendInFlight = false private var lastMarkedReadAt: Instant? = null private var isVisible = false + private val listingPhoto = + PhotoDownload(listingRepository::loadListingImage) { state, photo -> + state.copy(listingPhoto = photo) + } + private val otherUserPhoto = + PhotoDownload(profileRepository::loadProfilePhoto) { state, photo -> + state.copy(otherUserPhoto = photo) + } init { observeListing() @@ -276,6 +297,7 @@ class ConversationViewModel( _uiState.update { (if (clearError) it.copy(loadError = null) else it).derived() } updateLoading() observeOtherUser() + listingPhoto.show(loaded.listing?.imagePaths?.firstOrNull()) } private fun observeConversation() { @@ -351,7 +373,10 @@ class ConversationViewModel( // The chat works without the profile, so no error is shown; toAppError() still logs // unrecognised failures. .catch { exception -> exception.toAppError() } - .collect { user -> _uiState.update { it.copy(otherUser = user) } } + .collect { user -> + _uiState.update { it.copy(otherUser = user) } + otherUserPhoto.show(user?.photoPath) + } } } @@ -375,6 +400,7 @@ class ConversationViewModel( return copy( listingTitle = listing?.title ?: conversation?.listingTitle, listingStatus = status, + listing = listing, canSend = sendable, firstMessageBlockedByPause = status == ConversationListingStatus.PAUSED && @@ -383,4 +409,34 @@ class ConversationViewModel( conversationKnown, ) } + + /** + * One photo of the screen, set into the state by [set]. It is downloaded with [download] once per + * Storage path, and again only when the path changes, which drops the older photo and any + * download of it still running. A failed download, a stray [CancellationException] included, + * leaves the photo missing without an error: the screen shows a placeholder. Only used on the + * main thread. + */ + private inner class PhotoDownload( + private val download: suspend (String) -> ByteArray, + private val set: (ConversationUiState, ByteArray?) -> ConversationUiState, + ) { + private var path: String? = null + private var job: Job? = null + + fun show(newPath: String?) { + if (newPath == path) return + path = newPath + job?.cancel() + _uiState.update { set(it, null) } + if (newPath == null) return + job = viewModelScope.launch { + attempt { download(newPath) } + .onSuccess { photo -> + // A download that ignored its cancellation must not replace a newer photo. + if (path == newPath) _uiState.update { set(it, photo) } + } + } + } + } } 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 bb884ba0..80a907cb 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 @@ -110,7 +110,7 @@ class ConversationViewModelTest { val viewModel = viewModel() - assertEquals(ConversationUiState(myUid = renter.uid), viewModel.uiState.value) + assertEquals(ConversationUiState(myUid = renter.uid, isRenter = true), viewModel.uiState.value) advance() val state = viewModel.uiState.value assertFalse(state.isLoading) From 29f1b6011e18c6a0f7e6b14b008f1473c6e5a0e3 Mon Sep 17 00:00:00 2001 From: Alex Garcia <2alex.garcia2@gmail.com> Date: Tue, 17 Nov 2026 21:12:05 +0100 Subject: [PATCH 3/3] test(chat): cover the conversation's listing, role and photos --- .../viewmodel/ConversationViewModelTest.kt | 204 ++++++++++++++++++ .../profile/model/FakeProfileRepository.kt | 29 ++- 2 files changed, 225 insertions(+), 8 deletions(-) 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 80a907cb..1725074b 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 com.android.polybazaar.error.model.AppError import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.ListingCategory +import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.profile.model.FakeProfileRepository import com.google.firebase.firestore.FirebaseFirestoreException import java.net.UnknownHostException @@ -17,14 +18,18 @@ import java.time.Instant import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withContext import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame import org.junit.Assert.assertNull +import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -966,4 +971,203 @@ class ConversationViewModelTest { assertEquals(listOf(unreadReply.id), chat.markedRead) } + + @Test + fun listing_isExposed_andKeptAfterItIsDeleted() { + val viewModel = loadedViewModel() + assertEquals(listing, viewModel.uiState.value.listing) + + listings.allListings = emptyList() + advance() + + val state = viewModel.uiState.value + assertEquals(ConversationListingStatus.DELETED, state.listingStatus) + assertEquals(listing, state.listing) + } + + @Test + fun listing_deletedBeforeTheScreenOpened_isNull() { + listings = FakeListingRepository() + givenConversation(messages = arrayOf(hello)) + + val state = loadedViewModel().uiState.value + + assertEquals(ConversationListingStatus.DELETED, state.listingStatus) + assertNull(state.listing) + assertNull(state.listingPhoto) + assertEquals(0, listings.loadedImagePaths.size) + } + + @Test + fun isRenter_tellsTheRenterFromTheLender() { + assertTrue(viewModel(renter.uid).uiState.value.isRenter) + assertFalse(viewModel(lender.uid).uiState.value.isRenter) + } + + @Test + fun listingPhoto_isDownloadedOnce_andAgainOnlyWhenTheFirstPathChanges() { + val first = byteArrayOf(1) + val replaced = byteArrayOf(3) + listings.images["drill/1"] = first + listings.images["drill/3"] = replaced + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/1", "drill/2"))) + val viewModel = loadedViewModel() + assertSame(first, viewModel.uiState.value.listingPhoto) + + listings.allListings = + listOf(listing.copy(title = "Bosch drill and bits", imagePaths = listOf("drill/1"))) + advance() + assertEquals(listOf("drill/1"), listings.loadedImagePaths) + assertSame(first, viewModel.uiState.value.listingPhoto) + + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/3"))) + advance() + assertEquals(listOf("drill/1", "drill/3"), listings.loadedImagePaths) + assertSame(replaced, viewModel.uiState.value.listingPhoto) + } + + @Test + fun listingPhoto_isKeptAfterTheListingIsDeleted_andDroppedWhenTheListingLosesItsPhotos() { + val photo = byteArrayOf(1) + listings.images["drill/1"] = photo + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/1"))) + val viewModel = loadedViewModel() + + listings.allListings = emptyList() + advance() + assertSame(photo, viewModel.uiState.value.listingPhoto) + assertEquals(listOf("drill/1"), listings.loadedImagePaths) + + listings.allListings = listOf(listing) + advance() + assertNull(viewModel.uiState.value.listingPhoto) + } + + @Test + fun listingPhoto_failedDownload_isMissingWithoutError_andNotRetriedForTheSamePath() { + listings.imageFailure = UnknownHostException("offline") + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/1"))) + givenConversation(messages = arrayOf(hello)) + val viewModel = loadedViewModel() + + listings.allListings = listOf(listing.copy(title = "Renamed", imagePaths = listOf("drill/1"))) + advance() + + val state = viewModel.uiState.value + assertNull(state.listingPhoto) + assertNull(state.loadError) + assertEquals(listOf(hello), state.messages) + assertEquals(listOf("drill/1"), listings.loadedImagePaths) + } + + @Test + fun listingPhoto_aStaleDownloadFinishingAfterANewerPath_doesNotReplaceTheNewerPhoto() { + val stale = byteArrayOf(1) + val current = byteArrayOf(3) + listings.images["drill/3"] = current + val staleGate = CompletableDeferred() + // The old path's download ignores its cancellation, like a Storage call that can't be stopped, + // so only the ViewModel's own check keeps its photo out. + val repository = + object : ListingRepository by listings { + override suspend fun loadListingImage(imagePath: String): ByteArray = + if (imagePath == "drill/1") { + withContext(NonCancellable) { staleGate.await() } + stale + } else listings.loadListingImage(imagePath) + } + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/1"))) + val viewModel = + ConversationViewModel( + listing.listingId!!, + renter.uid, + renter.uid, + chat, + profiles, + repository, + ) + advance() + + listings.allListings = listOf(listing.copy(imagePaths = listOf("drill/3"))) + advance() + assertSame(current, viewModel.uiState.value.listingPhoto) + + staleGate.complete(Unit) + advance() + assertSame(current, viewModel.uiState.value.listingPhoto) + } + + @Test + fun otherUserPhoto_isDownloadedOnce() { + profiles = + FakeProfileRepository( + listOf(lender.copy(photoPath = "profiles/lender"), renter).associateBy { it.uid } + ) + givenConversation(messages = arrayOf(hello)) + + val state = loadedViewModel().uiState.value + + assertNotNull(state.otherUserPhoto) + assertEquals(mapOf("profiles/lender" to 1), profiles.photoLoads) + } + + @Test + fun otherUserPhoto_failedDownload_isMissingWithoutError() { + profiles = + FakeProfileRepository( + listOf(lender.copy(photoPath = "profiles/lender"), renter).associateBy { it.uid } + ) + profiles.failingPhotoPaths += "profiles/lender" + + val state = loadedViewModel().uiState.value + + assertEquals(lender.copy(photoPath = "profiles/lender"), state.otherUser) + assertNull(state.otherUserPhoto) + assertNull(state.loadError) + } + + @Test + fun otherUserWithoutAPhoto_downloadsNothing() { + val state = loadedViewModel().uiState.value + + assertEquals(lender, state.otherUser) + assertNull(state.otherUserPhoto) + assertTrue(profiles.photoLoads.isEmpty()) + } + + @Test + fun otherUserPhoto_isNotDownloadedAgainWhenTheProfileChangesWithTheSamePath() { + val withPhoto = lender.copy(photoPath = "profiles/lender") + profiles = FakeProfileRepository(listOf(withPhoto, renter).associateBy { it.uid }) + val viewModel = loadedViewModel() + val photo = viewModel.uiState.value.otherUserPhoto + + profiles.users = listOf(withPhoto.copy(bio = "Tools for rent"), renter).associateBy { it.uid } + advance() + + assertEquals("Tools for rent", viewModel.uiState.value.otherUser?.bio) + assertSame(photo, viewModel.uiState.value.otherUserPhoto) + assertEquals(mapOf("profiles/lender" to 1), profiles.photoLoads) + } + + @Test + fun otherUserPhoto_isReplacedWhenThePathChanges_andClearedWhenThePhotoIsRemoved() { + val withPhoto = lender.copy(photoPath = "profiles/lender") + profiles = FakeProfileRepository(listOf(withPhoto, renter).associateBy { it.uid }) + val viewModel = loadedViewModel() + val old = viewModel.uiState.value.otherUserPhoto + assertNotNull(old) + + profiles.users = + listOf(withPhoto.copy(photoPath = "profiles/lender-2"), renter).associateBy { it.uid } + advance() + val new = viewModel.uiState.value.otherUserPhoto + assertNotNull(new) + assertNotSame(old, new) + assertEquals(mapOf("profiles/lender" to 1, "profiles/lender-2" to 1), profiles.photoLoads) + + profiles.users = listOf(lender, renter).associateBy { it.uid } + advance() + assertNull(viewModel.uiState.value.otherUserPhoto) + } } diff --git a/app/src/test/java/com/android/polybazaar/profile/model/FakeProfileRepository.kt b/app/src/test/java/com/android/polybazaar/profile/model/FakeProfileRepository.kt index 28783d15..5a210e79 100644 --- a/app/src/test/java/com/android/polybazaar/profile/model/FakeProfileRepository.kt +++ b/app/src/test/java/com/android/polybazaar/profile/model/FakeProfileRepository.kt @@ -6,20 +6,33 @@ import com.android.polybazaar.auth.model.User import java.net.UnknownHostException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map /** * A [ProfileRepository] for tests. * * [observeProfile] emits the user with that uid from [users], or null when there is none, like the - * real repository for a missing profile. For a uid in [failingUids] it fails with [failure] - * instead, a network error unless the test sets another. [lookups] counts how many times each uid's - * profile was collected. Set [gate] to keep every lookup waiting until the test completes it, to - * look at one in progress. [loadProfilePhoto] returns an empty photo, counted per path in - * [photoLoads]. It waits for [photoGate] when set, and fails with [failure] for a path in - * [failingPhotoPaths]. The other calls do nothing. + * real repository for a missing profile, and emits again whenever a test sets [users], like a new + * snapshot. For a uid in [failingUids] it fails with [failure] instead, a network error unless the + * test sets another. [lookups] counts how many times each uid's profile was collected. Set [gate] + * to keep every lookup waiting until the test completes it, to look at one in progress. + * [loadProfilePhoto] returns an empty photo, counted per path in [photoLoads]. It waits for + * [photoGate] when set, and fails with [failure] for a path in [failingPhotoPaths]. The other calls + * do nothing. */ -class FakeProfileRepository(private val users: Map = emptyMap()) : ProfileRepository { +class FakeProfileRepository(users: Map = emptyMap()) : ProfileRepository { + // A flow, so that observeProfile sees every change a test makes. + private val usersFlow = MutableStateFlow(users) + + var users: Map + get() = usersFlow.value + set(value) { + usersFlow.value = value + } + val failingUids = mutableSetOf() var gate: CompletableDeferred? = null val failingPhotoPaths = mutableSetOf() @@ -41,7 +54,7 @@ class FakeProfileRepository(private val users: Map = emptyMap()) : lookupCounts[uid] = (lookupCounts[uid] ?: 0) + 1 gate?.await() if (uid in failingUids) throw failure - emit(users[uid]) + emitAll(usersFlow.map { it[uid] }) } override suspend fun uploadProfilePhoto(uid: String, photoUri: Uri) = ""