From 33909a7a072c84fdfb0c94f797d6c51ba1fd3ffd Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Tue, 17 Nov 2026 16:42:09 +0100 Subject: [PATCH 01/21] feat(chat): keep the conversation's camera photos in their own folder Co-Authored-By: Claude Opus 5.5 --- .../java/com/android/polybazaar/listing/model/PhotoStorage.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/src/main/java/com/android/polybazaar/listing/model/PhotoStorage.kt b/app/src/main/java/com/android/polybazaar/listing/model/PhotoStorage.kt index 155ce207..6ec81743 100644 --- a/app/src/main/java/com/android/polybazaar/listing/model/PhotoStorage.kt +++ b/app/src/main/java/com/android/polybazaar/listing/model/PhotoStorage.kt @@ -95,6 +95,9 @@ class FilePhotoStorage(context: Context, private val form: String) : PhotoStorag /** The folder of the form that edits a saved listing. */ const val EDIT_FORM = "edit" + /** The folder of the photos taken in a conversation, kept until they are sent. */ + const val CHAT_FORM = "chat" + /** * Both the name and the path of the files-path declared in res/xml/file_paths.xml. The * FileProvider shares its subfolders too, so each form's folder lives under it. From 4399cc877e37c70f3fff8b2337f6992f3a7a8bc7 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Tue, 17 Nov 2026 16:48:32 +0100 Subject: [PATCH 02/21] feat(chat): attach a photo to the draft Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 101 ++++++++++++++++-- .../polybazaar/ui/navigation/AppNavHost.kt | 6 ++ .../chat/ui/ConversationScreenTest.kt | 13 +++ .../viewmodel/ConversationViewModelTest.kt | 28 ++++- 4 files changed, 137 insertions(+), 11 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..ca873756 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 @@ -1,6 +1,7 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.viewmodel +import android.net.Uri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.polybazaar.auth.model.User @@ -14,6 +15,7 @@ import com.android.polybazaar.error.model.toAppError import com.android.polybazaar.listing.model.Listing import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.listing.model.ObservedListing +import com.android.polybazaar.listing.model.PhotoStorage import com.android.polybazaar.profile.model.ProfileRepository import java.time.Instant import java.util.concurrent.atomic.AtomicBoolean @@ -45,8 +47,11 @@ enum class ConversationListingStatus { * null until it is known. * @property otherUser profile of the other participant, or null while it loads, after a failure, or * when they have no profile. - * @property draft the message being typed. - * @property canSend whether the draft can be sent now. + * @property draft the message being typed, or the caption of [attachedPhoto] when there is one. + * @property attachedPhoto the photo picked or taken to send with the draft as its caption, if any. + * @property canAttachPhoto whether a photo can be attached: only once the conversation exists, + * since a photo cannot be its first message, and while the listing is known and not deleted. + * @property canSend whether the draft, or the attached photo with its caption, can be sent now. * @property firstMessageBlockedByPause true when the renter has no conversation yet and the listing * is paused: the rules refuse a first message until it is active again. False while the * conversation loads and after it failed to load, when whether it exists is unknown. @@ -64,6 +69,8 @@ data class ConversationUiState( val listingStatus: ConversationListingStatus? = null, val otherUser: User? = null, val draft: String = "", + val attachedPhoto: Uri? = null, + val canAttachPhoto: Boolean = false, val canSend: Boolean = false, val firstMessageBlockedByPause: Boolean = false, val isLoading: Boolean = true, @@ -81,6 +88,9 @@ private data class LoadedListing( * Shows and sends the messages between the renter [renterUid] and the owner of the listing * [listingId], as seen by [myUid], the signed-in user. * + * [photoStorage] keeps the photos taken with the camera until they are sent; photos picked from the + * gallery belong to the user and are never deleted. + * * The lender must only be routed here for a conversation that already exists: until then the * security rules refuse them the conversation and its messages, which shows as a load error. */ @@ -91,6 +101,7 @@ class ConversationViewModel( private val chatRepository: ChatRepository, private val profileRepository: ProfileRepository, private val listingRepository: ListingRepository, + private val photoStorage: PhotoStorage, ) : ViewModel() { private val _uiState = MutableStateFlow(ConversationUiState(myUid = myUid)) @@ -113,6 +124,10 @@ class ConversationViewModel( private var sendInFlight = false private var lastMarkedReadAt: Instant? = null private var isVisible = false + // The photo the camera app is taking, until it closes. + private var photoBeingTaken: Uri? = null + // Photos taken with the camera and not deleted yet, so gallery photos are never deleted. + private val takenPhotos = mutableSetOf() init { observeListing() @@ -135,13 +150,60 @@ class ConversationViewModel( _uiState.update { it.copy(draft = text).derived() } } + /** + * Attaches [photo], picked from the gallery, replacing the photo attached before. Ignored when a + * photo cannot be attached. + */ + fun attachPhoto(photo: Uri) { + if (!_uiState.value.canAttachPhoto) return + replaceAttachedPhoto(photo) + } + + /** + * Prepares a photo for the camera app to take and returns where it should write it, or null when + * a photo cannot be attached or the file cannot be created. Call [finishTakingPhoto] once the + * camera app closes. + */ + fun startTakingPhoto(): Uri? { + if (!_uiState.value.canAttachPhoto) return null + // A second tap before the camera app opened replaces the first photo, which stays empty. + photoBeingTaken?.let(photoStorage::delete) + photoBeingTaken = null + val photo = photoStorage.newPhoto() ?: return null + photoBeingTaken = photo.uri + return photo.cameraUri + } + + /** + * Attaches the photo the camera app took, or deletes its empty file if [saved] is false or a + * photo can no longer be attached. + */ + fun finishTakingPhoto(saved: Boolean) { + val photo = photoBeingTaken ?: return + photoBeingTaken = null + if (!saved || !_uiState.value.canAttachPhoto) { + photoStorage.delete(photo) + return + } + takenPhotos += photo + replaceAttachedPhoto(photo) + } + + /** Removes the attached photo, deleting it if it was taken with the camera. */ + fun removeAttachedPhoto() { + val photo = _uiState.value.attachedPhoto ?: return + _uiState.update { it.copy(attachedPhoto = null).derived() } + deleteIfTaken(photo) + } + /** * Queues the draft as a message: the first one creates the conversation, later ones reply in it. * Ignored when it cannot be sent or while the previous send call is still running. */ fun send() { val state = _uiState.value - if (!state.canSend || sendInFlight) return + // Sending the attached photo is not supported yet: Send stays a no-op until it is. + if (!state.canSend || sendInFlight || state.attachedPhoto != null) return // Before the conversation has loaded, a renter's message is sent as a first one: the merge // write becomes an update when the conversation exists, and the rules accept it. val target = state.conversation ?: firstConversation() ?: return @@ -193,6 +255,17 @@ class ConversationViewModel( _uiState.update { it.copy(sendError = null) } } + private fun replaceAttachedPhoto(photo: Uri) { + val replaced = _uiState.value.attachedPhoto + _uiState.update { it.copy(attachedPhoto = photo).derived() } + if (replaced != null && replaced != photo) deleteIfTaken(replaced) + } + + /** Deletes [photo] if it was taken with the camera; a gallery photo is left alone. */ + private fun deleteIfTaken(photo: Uri) { + if (takenPhotos.remove(photo)) photoStorage.delete(photo) + } + /** * The conversation the first message creates, or null when it cannot be created: the rules only * let the renter named in its ID create it. The repository sends the listing's current title in @@ -361,20 +434,28 @@ class ConversationViewModel( } /** - * This state with the fields that derive from the observed listing, the conversation and the - * draft recomputed. + * This state with the fields that derive from the observed listing, the conversation, the draft + * and the attached photo recomputed. */ private fun ConversationUiState.derived(): ConversationUiState { val (listing, status) = loaded + val listingOpen = status != null && status != ConversationListingStatus.DELETED + val canAttach = listingOpen && conversation != null val sendable = - ChatRules.isSendable(draft) && - status != null && - status != ConversationListingStatus.DELETED && - (conversation != null || - (status == ConversationListingStatus.ACTIVE && firstConversation(listing) != null)) + if (attachedPhoto != null) { + // A photo can be sent alone: a blank caption is no caption. + canAttach && (draft.isBlank() || ChatRules.isSendable(draft)) + } else { + ChatRules.isSendable(draft) && + listingOpen && + (conversation != null || + (status == ConversationListingStatus.ACTIVE && + firstConversation(listing) != null)) + } return copy( listingTitle = listing?.title ?: conversation?.listingTitle, listingStatus = status, + canAttachPhoto = canAttach, canSend = sendable, firstMessageBlockedByPause = status == ConversationListingStatus.PAUSED && diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index a9b25926..127a7d99 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -25,6 +25,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight @@ -69,6 +70,7 @@ import com.android.polybazaar.chat.viewmodel.ConversationViewModel import com.android.polybazaar.chat.viewmodel.InboxViewModel import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message +import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.listing.model.PhotoStorage import com.android.polybazaar.listing.ui.CreateListingScreen @@ -447,6 +449,9 @@ fun AppNavHost( // The route requires both, so they are always there. val listingId = entry.arguments!!.getString(Routes.LISTING_ID)!! val renterUid = entry.arguments!!.getString(Routes.RENTER_UID)!! + val appContext = LocalContext.current.applicationContext + val chatPhotoStorage = + remember(appContext) { FilePhotoStorage(appContext, FilePhotoStorage.CHAT_FORM) } // Scoped to this entry: each conversation opened gets its own ViewModel. val conversationViewModel: ConversationViewModel = viewModel( @@ -460,6 +465,7 @@ fun AppNavHost( chatRepository = chatRepository, profileRepository = profileRepository, listingRepository = listingRepository, + photoStorage = chatPhotoStorage, ) } } diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt index e2a27c36..602ac160 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt @@ -2,6 +2,7 @@ package com.android.polybazaar.chat.ui import android.content.Context +import android.net.Uri import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -50,6 +51,8 @@ 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.PhotoStorage +import com.android.polybazaar.listing.model.TakenPhoto import com.android.polybazaar.profile.model.FakeProfileRepository import java.net.UnknownHostException import java.time.Instant @@ -196,6 +199,7 @@ class ConversationScreenTest { chatRepository = chat, profileRepository = FakeProfileRepository(mapOf(james.uid to james)), listingRepository = listings, + photoStorage = NoPhotoStorage, ) composeTestRule.setContent { CompositionLocalProvider( @@ -830,4 +834,13 @@ class ConversationScreenTest { node(ConversationScreenTags.SEND_ERROR).assertDoesNotExist() node(ConversationScreenTags.MESSAGE_FIELD).assert(hasDraft("Is it free on Saturday?!")) } + + /** No test of the screen takes a photo yet. */ + private object NoPhotoStorage : PhotoStorage { + override fun newPhoto(): TakenPhoto? = null + + override fun delete(photo: Uri) = Unit + + override fun deleteAllExcept(keep: List) = Unit + } } 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..48fc221b 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 @@ -1,6 +1,7 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.viewmodel +import android.net.Uri import com.android.polybazaar.auth.model.User import com.android.polybazaar.chat.model.ChatMessage import com.android.polybazaar.chat.model.ChatRules @@ -10,6 +11,8 @@ 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.PhotoStorage +import com.android.polybazaar.listing.model.TakenPhoto import com.android.polybazaar.profile.model.FakeProfileRepository import com.google.firebase.firestore.FirebaseFirestoreException import java.net.UnknownHostException @@ -36,6 +39,7 @@ class ConversationViewModelTest { private lateinit var chat: FakeChatRepository private lateinit var profiles: FakeProfileRepository private lateinit var listings: FakeListingRepository + private lateinit var photoStorage: FakePhotoStorage private val lender = User(uid = "lender", email = "", username = "Lena") private val renter = User(uid = "renter", email = "", username = "Remi") @@ -69,6 +73,7 @@ class ConversationViewModelTest { chat = FakeChatRepository() profiles = FakeProfileRepository(listOf(lender, renter).associateBy { it.uid }) listings = FakeListingRepository(allListings = listOf(listing)) + photoStorage = FakePhotoStorage() } @After @@ -80,7 +85,15 @@ class ConversationViewModelTest { /** Creates the ViewModel for the drill conversation, seen by [myUid], without running it. */ private fun viewModel(myUid: String = renter.uid) = - ConversationViewModel(listing.listingId!!, renter.uid, myUid, chat, profiles, listings) + ConversationViewModel( + listing.listingId!!, + renter.uid, + myUid, + chat, + profiles, + listings, + photoStorage, + ) /** Creates the ViewModel and lets its loads finish. */ private fun loadedViewModel(myUid: String = renter.uid) = viewModel(myUid).also { advance() } @@ -966,4 +979,17 @@ class ConversationViewModelTest { assertEquals(listOf(unreadReply.id), chat.markedRead) } + + /** Records the photos deleted; it cannot create one, which no test needs yet. */ + private class FakePhotoStorage : PhotoStorage { + val deleted = mutableListOf() + + override fun newPhoto(): TakenPhoto? = null + + override fun delete(photo: Uri) { + deleted += photo + } + + override fun deleteAllExcept(keep: List) = Unit + } } From 8be72c2c814c46a782a419ec606c26f55c3676fd Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Tue, 17 Nov 2026 16:50:51 +0100 Subject: [PATCH 03/21] feat(chat): send a photo with its caption Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 117 +++++++++++++++++- 1 file changed, 114 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 ca873756..6fee9ffc 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 @@ -35,6 +35,28 @@ enum class ConversationListingStatus { DELETED, } +/** Where a photo being sent is. */ +enum class PendingPhotoStatus { + UPLOADING, + FAILED, +} + +/** + * A photo the user sent that is not in the conversation yet: still uploading, or failed. + * + * @property messageId the ID of its message, kept so a retry reuses the photo already uploaded. + * @property photo the photo on the device. + * @property caption the trimmed caption, or null for a photo alone. + * @property error why it failed, when [status] is [PendingPhotoStatus.FAILED]. + */ +data class PendingPhoto( + val messageId: String, + val photo: Uri, + val caption: String?, + val status: PendingPhotoStatus, + val error: AppError? = null, +) + /** * State of the conversation screen. * @@ -55,6 +77,7 @@ enum class ConversationListingStatus { * @property firstMessageBlockedByPause true when the renter has no conversation yet and the listing * is paused: the rules refuse a first message until it is active again. False while the * conversation loads and after it failed to load, when whether it exists is unknown. + * @property pendingPhotos the photos sent that are not in [messages] yet, oldest first. * @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 @@ -73,6 +96,7 @@ data class ConversationUiState( val canAttachPhoto: Boolean = false, val canSend: Boolean = false, val firstMessageBlockedByPause: Boolean = false, + val pendingPhotos: List = emptyList(), val isLoading: Boolean = true, val loadError: AppError? = null, val sendError: AppError? = null, @@ -198,12 +222,18 @@ class ConversationViewModel( /** * Queues the draft as a message: the first one creates the conversation, later ones reply in it. - * Ignored when it cannot be sent or while the previous send call is still running. + * With a photo attached, sends the photo with the draft as its caption instead. Ignored when it + * cannot be sent or while the previous text send call is still running. */ fun send() { val state = _uiState.value - // Sending the attached photo is not supported yet: Send stays a no-op until it is. - if (!state.canSend || sendInFlight || state.attachedPhoto != null) return + if (!state.canSend) return + val photo = state.attachedPhoto + if (photo != null) { + sendPhoto(state, photo) + return + } + if (sendInFlight) return // Before the conversation has loaded, a renter's message is sent as a first one: the merge // write becomes an update when the conversation exists, and the rules accept it. val target = state.conversation ?: firstConversation() ?: return @@ -251,6 +281,68 @@ class ConversationViewModel( if (messages) observeMessages() } + /** + * Sends the attached [photo] with the draft as its caption. Both are cleared at once, so a second + * tap on Send finds nothing to send, and the photo shows as uploading until it is sent. + */ + private fun sendPhoto(state: ConversationUiState, photo: Uri) { + // canSend only allows a photo once the conversation exists. + val conversation = state.conversation ?: return + val pending = + PendingPhoto( + messageId = chatRepository.newMessageId(conversation.id), + photo = photo, + caption = state.draft.trim().ifEmpty { null }, + status = PendingPhotoStatus.UPLOADING, + ) + _uiState.update { + it.copy(draft = "", attachedPhoto = null, pendingPhotos = it.pendingPhotos + pending) + .derived() + } + upload(conversation, pending) + } + + /** Sends [pending], then removes it once its message is queued, or marks it failed. */ + private fun upload(conversation: Conversation, pending: PendingPhoto) { + viewModelScope.launch { + val rejected = AtomicBoolean(false) + try { + chatRepository.sendPhoto( + conversation, + pending.messageId, + pending.photo, + pending.caption, + ) { exception -> + rejected.set(true) + onPhotoWriteFailure(pending, exception) + } + // Checked inside update so a rejection racing with this removal cannot be lost. + _uiState.update { + if (rejected.get()) it + else it.copy(pendingPhotos = it.pendingPhotos.filterNot { p -> p.isSameAs(pending) }) + } + // The upload is done: a retry after a late rejection reuses the uploaded file, not this + // one. + deleteIfTaken(pending.photo) + } catch (exception: Exception) { + if (exception is CancellationException) throw exception + val error = exception.toAppError() + _uiState.update { it.withPendingPhoto(pending.failed(error)) } + reloadListingAfter(error) + } + } + } + + /** + * Shows [pending] as failed again after the server rejected its message. Runs on any thread and + * must not throw: Firestore may call it from a background thread. + */ + private fun onPhotoWriteFailure(pending: PendingPhoto, exception: Exception) { + val error = exception.toAppError() + _uiState.update { it.withPendingPhoto(pending.failed(error)) } + reloadListingAfter(error) + } + fun dismissSendError() { _uiState.update { it.copy(sendError = null) } } @@ -261,6 +353,25 @@ class ConversationViewModel( if (replaced != null && replaced != photo) deleteIfTaken(replaced) } + private fun PendingPhoto.isSameAs(other: PendingPhoto) = messageId == other.messageId + + private fun PendingPhoto.failed(error: AppError) = + copy(status = PendingPhotoStatus.FAILED, error = error) + + /** + * This state with [photo] in place of the pending photo with its message ID, or added after the + * others when it was already removed, as after a late rejection. + */ + private fun ConversationUiState.withPendingPhoto(photo: PendingPhoto): ConversationUiState { + val photos = + if (pendingPhotos.any { it.isSameAs(photo) }) { + pendingPhotos.map { if (it.isSameAs(photo)) photo else it } + } else { + pendingPhotos + photo + } + return copy(pendingPhotos = photos) + } + /** Deletes [photo] if it was taken with the camera; a gallery photo is left alone. */ private fun deleteIfTaken(photo: Uri) { if (takenPhotos.remove(photo)) photoStorage.delete(photo) From 8c3ce26dec34d4630854a91dfcb0a56b57c3ac87 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Tue, 17 Nov 2026 17:04:04 +0100 Subject: [PATCH 04/21] feat(chat): retry or remove a photo that failed Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 44 +++++++++++++++++++ 1 file changed, 44 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 6fee9ffc..284ae179 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 @@ -333,6 +333,32 @@ class ConversationViewModel( } } + /** + * Sends the failed photo of [messageId] again, with the same message ID: the photo already + * uploaded is reused, and the rules refuse to overwrite it with another. Ignored unless it + * failed. + */ + fun retryPhoto(messageId: String) { + val state = _uiState.value + val failed = state.failedPhoto(messageId) ?: return + val conversation = state.conversation ?: return + val retried = failed.copy(status = PendingPhotoStatus.UPLOADING, error = null) + _uiState.update { it.withPendingPhoto(retried) } + upload(conversation, retried) + } + + /** + * Removes the failed photo of [messageId], deleting it if it was taken with the camera. Ignored + * unless it failed: an upload under way cannot be taken back. + */ + fun discardPhoto(messageId: String) { + val failed = _uiState.value.failedPhoto(messageId) ?: return + _uiState.update { + it.copy(pendingPhotos = it.pendingPhotos.filterNot { p -> p.isSameAs(failed) }) + } + deleteIfTaken(failed.photo) + } + /** * Shows [pending] as failed again after the server rejected its message. Runs on any thread and * must not throw: Firestore may call it from a background thread. @@ -347,12 +373,30 @@ class ConversationViewModel( _uiState.update { it.copy(sendError = null) } } + /** + * Deletes the photos taken with the camera that were not sent: the one being taken, the attached + * one and the failed ones. Gallery photos are left alone. + */ + override fun onCleared() { + photoBeingTaken?.let(photoStorage::delete) + // Closing the screen cancels the uploads under way, but compressing a photo is not cancelled + // mid-read, so their files are kept rather than deleted under it. They stay in the chat folder. + if (_uiState.value.pendingPhotos.any { it.status == PendingPhotoStatus.UPLOADING }) return + takenPhotos.forEach(photoStorage::delete) + takenPhotos.clear() + } + private fun replaceAttachedPhoto(photo: Uri) { val replaced = _uiState.value.attachedPhoto _uiState.update { it.copy(attachedPhoto = photo).derived() } if (replaced != null && replaced != photo) deleteIfTaken(replaced) } + private fun ConversationUiState.failedPhoto(messageId: String): PendingPhoto? = + pendingPhotos.find { + it.messageId == messageId && it.status == PendingPhotoStatus.FAILED + } + private fun PendingPhoto.isSameAs(other: PendingPhoto) = messageId == other.messageId private fun PendingPhoto.failed(error: AppError) = From 252101c5e39f4eb4849d94e6f09ecd94edc6771f Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Tue, 17 Nov 2026 17:33:32 +0100 Subject: [PATCH 05/21] feat(chat): pick or take a photo in the conversation Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 225 +++++++++++++++++- app/src/main/res/values/strings.xml | 6 + 2 files changed, 228 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 1bbdd0e2..4996820a 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt @@ -1,6 +1,11 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.ui +import android.net.Uri +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.PickVisualMediaRequest +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.layout.Arrangement @@ -20,21 +25,33 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource @@ -66,6 +83,9 @@ import com.android.polybazaar.chat.viewmodel.ConversationUiState import com.android.polybazaar.chat.viewmodel.ConversationViewModel 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.loadPhotoPreview +import com.android.polybazaar.listing.ui.rememberPhotoCamera import java.time.Instant import java.time.ZoneId import java.time.ZoneOffset @@ -88,6 +108,12 @@ object ConversationScreenTags { const val SEND_BUTTON = "conversation_send_button" const val SEND_ERROR = "conversation_send_error" const val LENGTH_COUNTER = "conversation_length_counter" + const val PHOTO_BUTTON = "conversation_photo_button" + const val PHOTO_MENU = "conversation_photo_menu" + const val TAKE_PHOTO = "conversation_take_photo" + const val CHOOSE_PHOTO = "conversation_choose_photo" + const val ATTACHED_PHOTO = "conversation_attached_photo" + const val REMOVE_ATTACHED_PHOTO = "conversation_remove_attached_photo" /** Tag of the bubble of the signed-in user's message with [id]. */ fun myMessage(id: String) = "conversation_my_message_$id" @@ -142,6 +168,16 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { viewModel.setVisible(true) onStopOrDispose { viewModel.setVisible(false) } } + val galleryPicker = + rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> + if (uri != null) viewModel.attachPhoto(uri) + } + // The ViewModel keeps the photo file, so it survives the activity being recreated meanwhile. + val camera = + rememberPhotoCamera( + startTakingPhoto = { _ -> viewModel.startTakingPhoto() }, + finishTakingPhoto = viewModel::finishTakingPhoto, + ) ConversationContent( uiState = uiState, onBack = onBack, @@ -149,7 +185,17 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { onSend = viewModel::send, onRetry = viewModel::retry, onDismissSendError = viewModel::dismissSendError, + onTakePhoto = camera::takePhoto, + onChoosePhoto = { + galleryPicker.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) + ) + }, + onRemoveAttachedPhoto = viewModel::removeAttachedPhoto, ) + if (camera.showPermissionExplanation) { + CameraPermissionDialog(onDismiss = camera::dismissPermissionExplanation) + } } /** @@ -165,6 +211,9 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { * @param onRetry called when the user taps Retry after a load failed. * @param onDismissSendError called before [onDraftChange] when the user edits the draft while a * send error shows. + * @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 zone time zone of the message times. */ @Composable @@ -175,6 +224,9 @@ fun ConversationContent( onSend: () -> Unit = {}, onRetry: () -> Unit = {}, onDismissSendError: () -> Unit = {}, + onTakePhoto: () -> Unit = {}, + onChoosePhoto: () -> Unit = {}, + onRemoveAttachedPhoto: () -> Unit = {}, zone: ZoneId = ZoneId.systemDefault(), ) { val body = conversationBody(uiState) @@ -183,7 +235,11 @@ fun ConversationContent( // canSend decides when Send works. val composerOpen = !deleted val placeholder = - if (deleted) R.string.conversation_placeholder_closed else R.string.conversation_placeholder + when { + deleted -> R.string.conversation_placeholder_closed + uiState.attachedPhoto != null -> R.string.conversation_placeholder_caption + else -> R.string.conversation_placeholder + } Column( modifier = Modifier.fillMaxSize() @@ -218,6 +274,14 @@ fun ConversationContent( onDraftChange(text) }, onSend = onSend, + photo = + ComposerPhoto( + attached = uiState.attachedPhoto, + canAttach = uiState.canAttachPhoto, + onTake = onTakePhoto, + onChoose = onChoosePhoto, + onRemove = onRemoveAttachedPhoto, + ), ) } } @@ -530,8 +594,21 @@ private fun MessageBubble( } /** - * The message field and Send, with why the last send failed under them and, once the draft is too - * long, a counter that explains why Send is disabled. The text is kept as typed. + * The composer's photo: the one attached, whether one can be attached, and what the user does with + * it. + */ +private class ComposerPhoto( + val attached: Uri?, + val canAttach: Boolean, + val onTake: () -> Unit, + val onChoose: () -> Unit, + val onRemove: () -> Unit, +) + +/** + * The photo button, the message field and Send, with the attached photo above them, and under them + * why the last send failed and, once the draft is too long, a counter that explains why Send is + * disabled. The text is kept as typed. * * @param open whether the user can type; Send also needs [canSend]. */ @@ -544,6 +621,7 @@ private fun Composer( sendError: AppError?, onDraftChange: (String) -> Unit, onSend: () -> Unit, + photo: ComposerPhoto, ) { val length = ChatRules.countedLength(draft) val tooLong = open && length > ChatRules.MAX_MESSAGE_LENGTH @@ -563,10 +641,12 @@ private fun Composer( .padding(horizontal = PageMargin, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { + photo.attached?.let { AttachedPhoto(photo = it, onRemove = photo.onRemove) } Row( horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.Bottom, ) { + PhotoButton(enabled = photo.canAttach, onTake = photo.onTake, onChoose = photo.onChoose) MessageField( value = draft, onValueChange = onDraftChange, @@ -626,6 +706,145 @@ private fun Composer( } } +/** The camera button left of the field, opening a menu to take a photo or choose one. */ +@Composable +private fun PhotoButton(enabled: Boolean, onTake: () -> Unit, onChoose: () -> Unit) { + var menuOpen by remember { mutableStateOf(false) } + val shape = RoundedCornerShape(14.dp) + Box { + IconButton( + onClick = { menuOpen = true }, + enabled = enabled, + modifier = + Modifier.size(48.dp) + .border(1.dp, AuthColors.Outline, shape) + .testTag(ConversationScreenTags.PHOTO_BUTTON), + ) { + Icon( + painter = painterResource(R.drawable.ic_camera), + contentDescription = stringResource(R.string.conversation_photo_button), + tint = if (enabled) AuthColors.TextPrimary else AuthColors.TextSecondary, + modifier = Modifier.size(20.dp), + ) + } + DropdownMenu( + expanded = menuOpen, + onDismissRequest = { menuOpen = false }, + containerColor = AuthColors.CardBackground, + modifier = Modifier.testTag(ConversationScreenTags.PHOTO_MENU), + ) { + PhotoMenuItem( + text = stringResource(R.string.conversation_take_photo), + icon = R.drawable.ic_camera, + tag = ConversationScreenTags.TAKE_PHOTO, + onClick = { + menuOpen = false + onTake() + }, + ) + PhotoMenuItem( + text = stringResource(R.string.conversation_choose_photo), + icon = R.drawable.ic_image, + tag = ConversationScreenTags.CHOOSE_PHOTO, + onClick = { + menuOpen = false + onChoose() + }, + ) + } + } +} + +@Composable +private fun PhotoMenuItem(text: String, icon: Int, tag: String, onClick: () -> Unit) { + DropdownMenuItem( + text = { Text(text = text, color = AuthColors.TextPrimary, fontSize = 14.sp) }, + // Decorative: the text says what the item does. + leadingIcon = { + Icon( + painter = painterResource(icon), + contentDescription = null, + tint = AuthColors.TextPrimary, + modifier = Modifier.size(20.dp), + ) + }, + onClick = onClick, + modifier = Modifier.testTag(tag), + ) +} + +/** The photo attached to the draft, as a thumbnail with ✕ in its corner to remove it. */ +@Composable +private fun AttachedPhoto(photo: Uri, onRemove: () -> Unit) { + val shape = RoundedCornerShape(12.dp) + val description = stringResource(R.string.conversation_attached_photo) + // The thumbnail with room around it for ✕, which overlaps its top-right corner. + Box(modifier = Modifier.size(80.dp)) { + PhotoOrPlaceholder( + photo = rememberLocalPhoto(photo), + description = description, + modifier = + Modifier.align(Alignment.BottomStart) + .size(64.dp) + .clip(shape) + .testTag(ConversationScreenTags.ATTACHED_PHOTO), + ) + IconButton( + onClick = onRemove, + modifier = + Modifier.align(Alignment.TopEnd) + .size(32.dp) + .testTag(ConversationScreenTags.REMOVE_ATTACHED_PHOTO), + ) { + Box( + modifier = + Modifier.size(20.dp) + .background(AuthColors.TextPrimary.copy(alpha = 0.7f), CircleShape), + contentAlignment = Alignment.Center, + ) { + Icon( + painter = painterResource(R.drawable.ic_close), + contentDescription = stringResource(R.string.conversation_remove_attached_photo), + tint = AuthColors.CardBackground, + modifier = Modifier.size(12.dp), + ) + } + } + } +} + +/** [photo] filling its bounds, or a plain placeholder of the same size until it is decoded. */ +@Composable +private fun PhotoOrPlaceholder(photo: ImageBitmap?, description: String, modifier: Modifier) { + if (photo != null) { + Image( + bitmap = photo, + contentDescription = description, + contentScale = ContentScale.Crop, + modifier = modifier, + ) + } else { + Box( + modifier = + modifier.background(AuthColors.Outline).semantics { contentDescription = description } + ) + } +} + +/** + * A photo on the device, decoded off the main thread and scaled down, or null while it decodes or + * when it cannot be read. + */ +@Composable +private fun rememberLocalPhoto(photo: Uri): ImageBitmap? { + val contentResolver = LocalContext.current.contentResolver + val bitmap by + produceState(initialValue = null, photo) { + value = loadPhotoPreview(contentResolver, photo) + } + return bitmap +} + /** A field styled like LabeledField's, that grows up to five lines as the message gets longer. */ @Composable private fun MessageField( diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ac2de988..0bccb36a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -92,6 +92,12 @@ Write a message… Conversation closed Send + Add a caption… + Add a photo + Take photo + Choose from gallery + Attached photo + Remove photo %1$d/%2$d Message too long: at most %d character From 428e17365fd630feeca1455d9f96f83616ed8e1c Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:40:13 +0100 Subject: [PATCH 06/21] feat(chat): show the photos being sent with their upload state Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 199 ++++++++++++++++-- app/src/main/res/values/strings.xml | 4 + 2 files changed, 182 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt index 4996820a..5570bc45 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 @@ -11,6 +11,7 @@ import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -21,6 +22,7 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items @@ -47,6 +49,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.SolidColor @@ -81,6 +84,8 @@ import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.viewmodel.ConversationListingStatus import com.android.polybazaar.chat.viewmodel.ConversationUiState import com.android.polybazaar.chat.viewmodel.ConversationViewModel +import com.android.polybazaar.chat.viewmodel.PendingPhoto +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 @@ -120,6 +125,15 @@ 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 bubble of the photo being sent, or that failed, with message ID [id]. */ + fun pendingPhoto(id: String) = "conversation_pending_photo_$id" + + /** Tag of Retry on the failed photo with message ID [id]. */ + fun retryPhoto(id: String) = "conversation_retry_photo_$id" + + /** Tag of Remove on the failed photo with message ID [id]. */ + fun discardPhoto(id: String) = "conversation_discard_photo_$id" } /** What the screen shows between the header and the composer, decided by [conversationBody]. */ @@ -150,6 +164,12 @@ private val PageMargin = 18.dp /** Widest a bubble gets, so a long message wraps instead of spanning the screen. */ private val MaxBubbleWidth = 300.dp +/** + * Height of a photo in its bubble, the same while it loads, so the list does not jump when it + * arrives. + */ +private val BubblePhotoHeight = 200.dp + private val TimeFormat = DateTimeFormatter.ofPattern("HH:mm") /** @@ -192,6 +212,8 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { ) }, onRemoveAttachedPhoto = viewModel::removeAttachedPhoto, + onRetryPhoto = viewModel::retryPhoto, + onDiscardPhoto = viewModel::discardPhoto, ) if (camera.showPermissionExplanation) { CameraPermissionDialog(onDismiss = camera::dismissPermissionExplanation) @@ -214,6 +236,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 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. */ @Composable @@ -227,6 +251,8 @@ fun ConversationContent( onTakePhoto: () -> Unit = {}, onChoosePhoto: () -> Unit = {}, onRemoveAttachedPhoto: () -> Unit = {}, + onRetryPhoto: (String) -> Unit = {}, + onDiscardPhoto: (String) -> Unit = {}, zone: ZoneId = ZoneId.systemDefault(), ) { val body = conversationBody(uiState) @@ -260,7 +286,13 @@ fun ConversationContent( listingTitle = uiState.listingTitle, listingStatus = uiState.listingStatus, ) - ConversationBody.MESSAGES -> MessageList(uiState = uiState, zone = zone, onRetry = onRetry) + ConversationBody.MESSAGES -> + MessageList( + uiState = uiState, + zone = zone, + onRetry = onRetry, + photoActions = PhotoActions(onRetryPhoto, onDiscardPhoto), + ) } } Composer( @@ -471,15 +503,31 @@ private fun EmptyState( } } +/** What the user can do with the photos being sent. */ +private class PhotoActions( + val retry: (messageId: String) -> Unit, + val discard: (messageId: String) -> Unit, +) + /** - * The messages, oldest at the top, with the load error and Retry above them when a reload failed. + * The messages, oldest at the top, then the photos being sent, with the load error and Retry above + * them when a reload failed. */ @Composable -private fun MessageList(uiState: ConversationUiState, zone: ZoneId, onRetry: () -> Unit) { +private fun MessageList( + uiState: ConversationUiState, + zone: ZoneId, + onRetry: () -> Unit, + photoActions: PhotoActions, +) { val messages = uiState.messages + val pendingPhotos = uiState.pendingPhotos val listState = rememberLazyListState() - // The list keeps its place by key, so a new message would arrive below the view without this. - LaunchedEffect(messages.lastOrNull()?.id) { listState.scrollToItem(0) } + // 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) { + listState.scrollToItem(0) + } Column(modifier = Modifier.fillMaxSize()) { uiState.loadError?.let { LoadErrorRow(text = it.message(), onRetry = onRetry) } // Laid out from the bottom, newest first, so the newest message stays in view, footer @@ -491,6 +539,14 @@ private fun MessageList(uiState: ConversationUiState, zone: ZoneId, onRetry: () reverseLayout = true, verticalArrangement = Arrangement.spacedBy(8.dp), ) { + // Prefixed: once sent, a photo's message arrives with the same ID. + items(pendingPhotos.asReversed(), key = { "pending_${it.messageId}" }) { pending -> + PendingPhotoBubble( + pending = pending, + onRetry = { photoActions.retry(pending.messageId) }, + onDiscard = { photoActions.discard(pending.messageId) }, + ) + } items(messages.asReversed(), key = { it.id }) { message -> MessageBubble( message = message, @@ -553,6 +609,37 @@ private fun MessageBubble( stringResource(R.string.conversation_their_message_footer, otherUsername, time) else -> time } + Bubble( + isMine = isMine, + tag = + if (isMine) ConversationScreenTags.myMessage(message.id) + else ConversationScreenTags.theirMessage(message.id), + fixedWidth = false, + ) { + Text( + text = message.text, + color = AuthColors.TextPrimary, + fontSize = 14.sp, + lineHeight = 19.sp, + ) + BubbleFooter(text = footer) + } +} + +/** + * A message bubble: the user's own at the end of the row, the other participant's at the start. One + * TalkBack item: its photo, its text, then who sent it and when. + * + * @param fixedWidth whether the bubble is always [MaxBubbleWidth] wide, as for a photo, rather than + * as wide as its text. + */ +@Composable +private fun Bubble( + isMine: Boolean, + tag: String, + fixedWidth: Boolean, + content: @Composable ColumnScope.() -> Unit, +) { val shape = RoundedCornerShape(16.dp) Box( modifier = Modifier.fillMaxWidth(), @@ -560,14 +647,10 @@ private fun MessageBubble( ) { Column( modifier = - Modifier.widthIn(max = MaxBubbleWidth) - // One TalkBack item per message, the whole bubble: its text, then who sent it and - // when. + (if (fixedWidth) Modifier.width(MaxBubbleWidth) + else Modifier.widthIn(max = MaxBubbleWidth)) .semantics(mergeDescendants = true) {} - .testTag( - if (isMine) ConversationScreenTags.myMessage(message.id) - else ConversationScreenTags.theirMessage(message.id) - ) + .testTag(tag) .background( if (isMine) AuthColors.AccentContainer else AuthColors.CardBackground, shape, @@ -577,18 +660,92 @@ private fun MessageBubble( .padding(horizontal = 12.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text( - text = message.text, - color = AuthColors.TextPrimary, - fontSize = 14.sp, - lineHeight = 19.sp, + content() + } + } +} + +@Composable +private fun ColumnScope.BubbleFooter(text: String) { + Text( + text = text, + color = AuthColors.TextSecondary, + fontSize = 11.sp, + modifier = Modifier.align(Alignment.End), + ) +} + +/** + * 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. + */ +@Composable +private fun PendingPhotoBubble(pending: PendingPhoto, onRetry: () -> Unit, onDiscard: () -> Unit) { + val description = stringResource(R.string.conversation_photo) + val uploading = pending.status == PendingPhotoStatus.UPLOADING + Bubble( + isMine = true, + tag = ConversationScreenTags.pendingPhoto(pending.messageId), + fixedWidth = true, + ) { + Box(contentAlignment = Alignment.Center) { + // A taken photo is deleted once uploaded, so after a late rejection only the placeholder + // shows. + PhotoOrPlaceholder( + photo = rememberLocalPhoto(pending.photo), + description = description, + modifier = + Modifier.fillMaxWidth() + .height(BubblePhotoHeight) + .clip(RoundedCornerShape(10.dp)) + .alpha(0.6f), ) + if (uploading) { + CircularProgressIndicator( + color = AuthColors.CardBackground, + strokeWidth = 2.dp, + modifier = Modifier.size(24.dp), + ) + } + } + pending.caption?.let { + Text(text = it, color = AuthColors.TextPrimary, fontSize = 14.sp, lineHeight = 19.sp) + } + if (uploading) { + BubbleFooter(text = stringResource(R.string.conversation_photo_sending)) + } else { Text( - text = footer, - color = AuthColors.TextSecondary, - fontSize = 11.sp, - modifier = Modifier.align(Alignment.End), + text = + stringResource( + R.string.conversation_photo_not_sent, + (pending.error ?: AppError.UNKNOWN).message(), + ), + color = AuthColors.Danger, + fontSize = 12.sp, + // Announced when it fails: TalkBack's focus is elsewhere, on Send or the field. + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, ) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + TextButton( + onClick = onRetry, + modifier = Modifier.testTag(ConversationScreenTags.retryPhoto(pending.messageId)), + ) { + Text( + text = stringResource(R.string.conversation_retry), + color = AuthColors.Accent, + fontWeight = FontWeight.SemiBold, + ) + } + TextButton( + onClick = onDiscard, + modifier = Modifier.testTag(ConversationScreenTags.discardPhoto(pending.messageId)), + ) { + Text( + text = stringResource(R.string.conversation_photo_remove), + color = AuthColors.TextSecondary, + ) + } + } } } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0bccb36a..d62ee84e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -98,6 +98,10 @@ Choose from gallery Attached photo Remove photo + Photo + Sending… + Not sent. %1$s + Remove %1$d/%2$d Message too long: at most %d character From 7e5b5c11f256b4adae07a1140640e0ffb118a282 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 01:34:07 +0100 Subject: [PATCH 07/21] refactor(chat): drop the photo write callback sendPhoto now waits for the server and throws every failure, so the ViewModel no longer needs a callback for a late rejection: a photo leaves the pending list once sendPhoto returns. Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 3 +- .../chat/viewmodel/ConversationViewModel.kt | 40 +++++-------------- 2 files changed, 11 insertions(+), 32 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 5570bc45..4f385ba1 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 @@ -689,8 +689,7 @@ private fun PendingPhotoBubble(pending: PendingPhoto, onRetry: () -> Unit, onDis fixedWidth = true, ) { Box(contentAlignment = Alignment.Center) { - // A taken photo is deleted once uploaded, so after a late rejection only the placeholder - // shows. + // The placeholder shows when the photo on the device can no longer be read. PhotoOrPlaceholder( photo = rememberLocalPhoto(pending.photo), description = description, 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 284ae179..f8c6b70d 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 @@ -44,7 +44,7 @@ enum class PendingPhotoStatus { /** * A photo the user sent that is not in the conversation yet: still uploading, or failed. * - * @property messageId the ID of its message, kept so a retry reuses the photo already uploaded. + * @property messageId the ID of its message, kept so a retry reuses what is already on the server. * @property photo the photo on the device. * @property caption the trimmed caption, or null for a photo alone. * @property error why it failed, when [status] is [PendingPhotoStatus.FAILED]. @@ -302,27 +302,17 @@ class ConversationViewModel( upload(conversation, pending) } - /** Sends [pending], then removes it once its message is queued, or marks it failed. */ + /** + * Sends [pending], then removes it once the server has its message and photo, or marks it failed. + */ private fun upload(conversation: Conversation, pending: PendingPhoto) { viewModelScope.launch { - val rejected = AtomicBoolean(false) try { - chatRepository.sendPhoto( - conversation, - pending.messageId, - pending.photo, - pending.caption, - ) { exception -> - rejected.set(true) - onPhotoWriteFailure(pending, exception) - } - // Checked inside update so a rejection racing with this removal cannot be lost. + chatRepository.sendPhoto(conversation, pending.messageId, pending.photo, pending.caption) _uiState.update { - if (rejected.get()) it - else it.copy(pendingPhotos = it.pendingPhotos.filterNot { p -> p.isSameAs(pending) }) + it.copy(pendingPhotos = it.pendingPhotos.filterNot { p -> p.isSameAs(pending) }) } - // The upload is done: a retry after a late rejection reuses the uploaded file, not this - // one. + // Sent: nothing can fail any more, so the taken photo is no longer needed. deleteIfTaken(pending.photo) } catch (exception: Exception) { if (exception is CancellationException) throw exception @@ -334,9 +324,9 @@ class ConversationViewModel( } /** - * Sends the failed photo of [messageId] again, with the same message ID: the photo already - * uploaded is reused, and the rules refuse to overwrite it with another. Ignored unless it - * failed. + * Sends the failed photo of [messageId] again, with the same message ID: a message or photo + * already on the server is reused, since the rules refuse to write either twice. Ignored unless + * it failed. */ fun retryPhoto(messageId: String) { val state = _uiState.value @@ -359,16 +349,6 @@ class ConversationViewModel( deleteIfTaken(failed.photo) } - /** - * Shows [pending] as failed again after the server rejected its message. Runs on any thread and - * must not throw: Firestore may call it from a background thread. - */ - private fun onPhotoWriteFailure(pending: PendingPhoto, exception: Exception) { - val error = exception.toAppError() - _uiState.update { it.withPendingPhoto(pending.failed(error)) } - reloadListingAfter(error) - } - fun dismissSendError() { _uiState.update { it.copy(sendError = null) } } From 44580ca18e71fd878ed8f4b5ba7c07c61c7539e7 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:00:07 +0100 Subject: [PATCH 08/21] test(chat): cover attaching a photo Co-Authored-By: Claude Opus 5.5 --- .../viewmodel/ConversationViewModelTest.kt | 275 +++++++++++++++++- 1 file changed, 273 insertions(+), 2 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 48fc221b..d768cf36 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 @@ -2,6 +2,11 @@ package com.android.polybazaar.chat.viewmodel import android.net.Uri +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.viewmodel.initializer +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.ChatRules @@ -31,8 +36,10 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +import org.junit.runner.RunWith @OptIn(ExperimentalCoroutinesApi::class) +@RunWith(AndroidJUnit4::class) class ConversationViewModelTest { private val testDispatcher = StandardTestDispatcher() @@ -980,11 +987,275 @@ class ConversationViewModelTest { assertEquals(listOf(unreadReply.id), chat.markedRead) } - /** Records the photos deleted; it cannot create one, which no test needs yet. */ + // Photos + + private val galleryPhoto = Uri.parse("content://media/picker/1") + private val otherGalleryPhoto = Uri.parse("content://media/picker/2") + + /** Creates the ViewModel on the existing drill conversation and lets it load. */ + private fun inConversation(myUid: String = renter.uid): ConversationViewModel { + givenConversation() + return loadedViewModel(myUid) + } + + /** Takes a photo with the camera and attaches it; returns its file. */ + private fun ConversationViewModel.takePhoto(): Uri { + assertNotNull(startTakingPhoto()) + finishTakingPhoto(saved = true) + return photoStorage.taken.last().uri + } + + /** Closes the screen: clears the ViewModel the way its ViewModelStore does. */ + private fun ConversationViewModel.close() { + val store = ViewModelStore() + val factory = viewModelFactory { initializer { this@close } } + ViewModelProvider.create(store, factory)[ConversationViewModel::class] + store.clear() + } + + @Test + fun attachPhoto_fromTheGallery_attachesIt_andItCanBeSentWithoutACaption() { + val viewModel = inConversation() + assertTrue(viewModel.uiState.value.canAttachPhoto) + + viewModel.attachPhoto(galleryPhoto) + + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + assertTrue(viewModel.uiState.value.canSend) + } + + @Test + fun attachPhoto_beforeTheConversationExists_isIgnored() { + val viewModel = loadedViewModel() + + viewModel.attachPhoto(galleryPhoto) + + assertFalse(viewModel.uiState.value.canAttachPhoto) + assertNull(viewModel.uiState.value.attachedPhoto) + assertFalse(viewModel.uiState.value.canSend) + } + + @Test + fun attachPhoto_toADeletedListing_isIgnored() { + listings.allListings = emptyList() + val viewModel = inConversation() + + viewModel.attachPhoto(galleryPhoto) + + assertFalse(viewModel.uiState.value.canAttachPhoto) + assertNull(viewModel.uiState.value.attachedPhoto) + } + + @Test + fun attachPhoto_whileTheListingIsUnknown_isIgnored() { + listings.gate = CompletableDeferred() + val viewModel = inConversation() + + viewModel.attachPhoto(galleryPhoto) + + assertFalse(viewModel.uiState.value.canAttachPhoto) + assertNull(viewModel.uiState.value.attachedPhoto) + } + + @Test + fun takePhoto_saved_attachesTheTakenFile() { + val viewModel = inConversation() + + val cameraUri = viewModel.startTakingPhoto() + viewModel.finishTakingPhoto(saved = true) + + val taken = photoStorage.taken.single() + assertEquals(taken.cameraUri, cameraUri) + assertEquals(taken.uri, viewModel.uiState.value.attachedPhoto) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun takePhoto_cancelled_deletesTheFile_andAttachesNothing() { + val viewModel = inConversation() + + viewModel.startTakingPhoto() + viewModel.finishTakingPhoto(saved = false) + + assertNull(viewModel.uiState.value.attachedPhoto) + assertEquals(listOf(photoStorage.taken.single().uri), photoStorage.deleted) + } + + @Test + fun startTakingPhoto_againBeforeTheCameraCloses_deletesTheFirstFile() { + val viewModel = inConversation() + + viewModel.startTakingPhoto() + viewModel.startTakingPhoto() + viewModel.finishTakingPhoto(saved = true) + + val (first, second) = photoStorage.taken + assertEquals(listOf(first.uri), photoStorage.deleted) + assertEquals(second.uri, viewModel.uiState.value.attachedPhoto) + } + + @Test + fun startTakingPhoto_beforeTheConversationExists_returnsNullAndCreatesNoFile() { + val viewModel = loadedViewModel() + + assertNull(viewModel.startTakingPhoto()) + assertEquals(emptyList(), photoStorage.taken) + } + + @Test + fun startTakingPhoto_whenTheFileCannotBeCreated_returnsNull() { + photoStorage.full = true + val viewModel = inConversation() + + assertNull(viewModel.startTakingPhoto()) + viewModel.finishTakingPhoto(saved = true) + + assertNull(viewModel.uiState.value.attachedPhoto) + } + + @Test + fun finishTakingPhoto_withoutAPhotoBeingTaken_doesNothing() { + val viewModel = inConversation() + + viewModel.finishTakingPhoto(saved = true) + + assertNull(viewModel.uiState.value.attachedPhoto) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun finishTakingPhoto_onceAPhotoCanNoLongerBeAttached_deletesIt() { + val viewModel = inConversation() + viewModel.startTakingPhoto() + + chat.myConversations.value = Result.success(emptyList()) + advance() + viewModel.finishTakingPhoto(saved = true) + + assertNull(viewModel.uiState.value.attachedPhoto) + assertEquals(listOf(photoStorage.taken.single().uri), photoStorage.deleted) + } + + @Test + fun attachingAnotherPhoto_replacesATakenOne_andDeletesIt() { + val viewModel = inConversation() + val taken = viewModel.takePhoto() + + viewModel.attachPhoto(galleryPhoto) + + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun attachingAnotherPhoto_replacesAGalleryOne_withoutDeletingIt() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.attachPhoto(otherGalleryPhoto) + + assertEquals(otherGalleryPhoto, viewModel.uiState.value.attachedPhoto) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun attachingTheSamePhotoAgain_keepsIt() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.attachPhoto(galleryPhoto) + + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + } + + @Test + fun removeAttachedPhoto_deletesATakenPhoto() { + val viewModel = inConversation() + val taken = viewModel.takePhoto() + + viewModel.removeAttachedPhoto() + + assertNull(viewModel.uiState.value.attachedPhoto) + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun removeAttachedPhoto_keepsAGalleryPhoto() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.removeAttachedPhoto() + + assertNull(viewModel.uiState.value.attachedPhoto) + assertFalse(viewModel.uiState.value.canSend) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun canSend_withAPhoto_acceptsNoCaptionOrAValidOne_butNotATooLongOne() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + fun canSend(caption: String): Boolean { + viewModel.onDraftChange(caption) + return viewModel.uiState.value.canSend + } + + assertTrue(canSend("")) + assertTrue(canSend(" ")) + assertTrue(canSend("Here it is")) + assertTrue(canSend("a".repeat(ChatRules.MAX_MESSAGE_LENGTH))) + assertFalse(canSend("a".repeat(ChatRules.MAX_MESSAGE_LENGTH + 1))) + } + + @Test + fun closing_whileTheCameraIsOpen_deletesThePhotoBeingTaken() { + val viewModel = inConversation() + viewModel.startTakingPhoto() + + viewModel.close() + + assertEquals(listOf(photoStorage.taken.single().uri), photoStorage.deleted) + } + + @Test + fun closing_deletesTheAttachedTakenPhoto() { + val viewModel = inConversation() + val taken = viewModel.takePhoto() + + viewModel.close() + + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun closing_keepsAnAttachedGalleryPhoto() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.close() + + assertEquals(emptyList(), photoStorage.deleted) + } + + /** + * Creates photos like the camera folder: "taken_0", "taken_1", … in [taken], or none while + * [full]. Records the photos deleted. + */ private class FakePhotoStorage : PhotoStorage { + var full = false + val taken = mutableListOf() val deleted = mutableListOf() - override fun newPhoto(): TakenPhoto? = null + override fun newPhoto(): TakenPhoto? { + if (full) return null + val index = taken.size + return TakenPhoto( + uri = Uri.parse("file:///chat/taken_$index.jpg"), + cameraUri = Uri.parse("content://camera/taken_$index.jpg"), + ) + .also(taken::add) + } override fun delete(photo: Uri) { deleted += photo From 694e9f6ca8a5834fe79e175143c708dedcc2db21 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:01:06 +0100 Subject: [PATCH 09/21] test(chat): cover sending a photo Co-Authored-By: Claude Opus 5.5 --- .../viewmodel/ConversationViewModelTest.kt | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) 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 d768cf36..1f9cd871 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 @@ -1238,6 +1238,152 @@ class ConversationViewModelTest { assertEquals(emptyList(), photoStorage.deleted) } + @Test + fun sendPhoto_sendsTheConversationAFreshIdThePhotoAndTheTrimmedCaption() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + viewModel.onDraftChange(" Here it is ") + + viewModel.send() + advance() + + assertEquals( + listOf(FakeChatRepository.SentPhoto(conversation, "m1", galleryPhoto, "Here it is")), + chat.sentPhotos, + ) + assertEquals(emptyList>(), chat.sentMessages) + } + + @Test + fun sendPhoto_withABlankCaption_sendsNoCaption() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + viewModel.onDraftChange(" ") + + viewModel.send() + advance() + + assertNull(chat.sentPhotos.single().caption) + } + + @Test + fun sendPhoto_clearsTheAttachmentAndTheDraftAtOnce() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + viewModel.onDraftChange("Here it is") + + viewModel.send() + + val state = viewModel.uiState.value + assertNull(state.attachedPhoto) + assertEquals("", state.draft) + assertFalse(state.canSend) + assertEquals( + listOf(PendingPhoto("m1", galleryPhoto, "Here it is", PendingPhotoStatus.UPLOADING)), + state.pendingPhotos, + ) + } + + @Test + fun sendPhoto_staysUploadingUntilTheSendReturns_thenIsRemoved() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + assertEquals( + listOf(PendingPhotoStatus.UPLOADING), + viewModel.uiState.value.pendingPhotos.map { it.status }, + ) + + chat.gate!!.complete(Unit) + advance() + + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + } + + @Test + fun sendPhoto_tappedTwice_sendsOnce() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.send() + viewModel.send() + advance() + + assertEquals(1, chat.sentPhotos.size) + } + + @Test + fun sendPhoto_whileAnotherUploads_sendsBothWithTheirOwnIds() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + viewModel.attachPhoto(otherGalleryPhoto) + viewModel.send() + advance() + + assertEquals(listOf("m1", "m2"), chat.sentPhotos.map { it.messageId }) + assertEquals( + listOf(galleryPhoto, otherGalleryPhoto), + viewModel.uiState.value.pendingPhotos.map { it.photo }, + ) + } + + @Test + fun sentTakenPhoto_isDeletedOnceSent() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + val taken = viewModel.takePhoto() + viewModel.send() + advance() + assertEquals(emptyList(), photoStorage.deleted) + + chat.gate!!.complete(Unit) + advance() + + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun sentGalleryPhoto_isNotDeleted() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.send() + advance() + + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun send_withoutAPhoto_stillSendsTheText() { + val viewModel = inConversation() + viewModel.onDraftChange("Hello") + + viewModel.send() + advance() + + assertEquals(listOf(conversation to "Hello"), chat.sentMessages) + assertEquals(emptyList(), chat.sentPhotos) + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + } + + @Test + fun closing_whileAPhotoUploads_keepsTheTakenPhotos() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.takePhoto() + viewModel.send() + advance() + viewModel.takePhoto() + + viewModel.close() + + assertEquals(emptyList(), photoStorage.deleted) + } + /** * Creates photos like the camera folder: "taken_0", "taken_1", … in [taken], or none while * [full]. Records the photos deleted. From 8cc05e19c9a3b374d3a593716dc43d7755bc2b19 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:40:57 +0100 Subject: [PATCH 10/21] test(chat): cover a photo that fails to send Co-Authored-By: Claude Opus 5.5 --- .../viewmodel/ConversationViewModelTest.kt | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) 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 1f9cd871..ba198a89 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 @@ -13,6 +13,7 @@ import com.android.polybazaar.chat.model.ChatRules import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.model.FakeChatRepository import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.error.model.AppException import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.ListingCategory @@ -1384,6 +1385,166 @@ class ConversationViewModelTest { assertEquals(emptyList(), photoStorage.deleted) } + private val offline = AppException(AppError.NETWORK) + private val refused = firestoreError(FirebaseFirestoreException.Code.PERMISSION_DENIED) + + /** Attaches the gallery photo and sends it, failing with [failure]; returns the ViewModel. */ + private fun failedPhotoSend(failure: Exception): ConversationViewModel { + val viewModel = inConversation() + chat.sendFailure = failure + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + return viewModel + } + + @Test + fun sendPhoto_offline_failsWithNetwork() { + val viewModel = failedPhotoSend(offline) + + assertEquals( + listOf(PendingPhoto("m1", galleryPhoto, null, PendingPhotoStatus.FAILED, AppError.NETWORK)), + viewModel.uiState.value.pendingPhotos, + ) + assertNull(viewModel.uiState.value.sendError) + assertEquals(1, listings.getListingCalls) + } + + @Test + fun sendPhoto_refused_failsWithPermissionDenied_andReloadsTheListing() { + val viewModel = failedPhotoSend(refused) + + val pending = viewModel.uiState.value.pendingPhotos.single() + assertEquals(PendingPhotoStatus.FAILED, pending.status) + assertEquals(AppError.PERMISSION_DENIED, pending.error) + assertEquals(2, listings.getListingCalls) + } + + @Test + fun sendPhoto_toADeletedListing_reloadsItAndStopsAttachingPhotos() { + val viewModel = inConversation() + listings.allListings = emptyList() + chat.sendFailure = firestoreError(FirebaseFirestoreException.Code.NOT_FOUND) + viewModel.attachPhoto(galleryPhoto) + + viewModel.send() + advance() + + val state = viewModel.uiState.value + assertEquals(AppError.NOT_FOUND, state.pendingPhotos.single().error) + assertEquals(ConversationListingStatus.DELETED, state.listingStatus) + assertFalse(state.canAttachPhoto) + } + + @Test + fun retryPhoto_sendsAgainWithTheSameMessageId_andRemovesItOnceSent() { + val viewModel = failedPhotoSend(offline) + chat.sendFailure = null + chat.gate = CompletableDeferred() + + viewModel.retryPhoto("m1") + advance() + val retried = viewModel.uiState.value.pendingPhotos.single() + assertEquals(PendingPhotoStatus.UPLOADING, retried.status) + assertNull(retried.error) + + chat.gate!!.complete(Unit) + advance() + assertEquals(listOf("m1", "m1"), chat.sentPhotos.map { it.messageId }) + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + } + + @Test + fun retryPhoto_failingAgain_isFailedAgainWithTheNewError() { + val viewModel = failedPhotoSend(offline) + chat.sendFailure = refused + + viewModel.retryPhoto("m1") + advance() + + val pending = viewModel.uiState.value.pendingPhotos.single() + assertEquals(PendingPhotoStatus.FAILED, pending.status) + assertEquals(AppError.PERMISSION_DENIED, pending.error) + } + + @Test + fun retryPhoto_whileItUploads_doesNotSendItTwice() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + + viewModel.retryPhoto("m1") + advance() + + assertEquals(1, chat.sentPhotos.size) + } + + @Test + fun retryPhoto_ofAnUnknownId_doesNothing() { + val viewModel = failedPhotoSend(offline) + + viewModel.retryPhoto("m9") + advance() + + assertEquals(1, chat.sentPhotos.size) + assertEquals(PendingPhotoStatus.FAILED, viewModel.uiState.value.pendingPhotos.single().status) + } + + @Test + fun discardPhoto_removesAFailedTakenPhoto_andDeletesItsFile() { + val viewModel = inConversation() + chat.sendFailure = offline + val taken = viewModel.takePhoto() + viewModel.send() + advance() + + viewModel.discardPhoto("m1") + + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun discardPhoto_removesAFailedGalleryPhoto_withoutDeletingIt() { + val viewModel = failedPhotoSend(offline) + + viewModel.discardPhoto("m1") + + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun discardPhoto_whileItUploads_isIgnored() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + + viewModel.discardPhoto("m1") + + assertEquals( + listOf(PendingPhotoStatus.UPLOADING), + viewModel.uiState.value.pendingPhotos.map { it.status }, + ) + } + + @Test + fun closing_withAFailedTakenPhoto_deletesIt() { + val viewModel = inConversation() + chat.sendFailure = offline + val taken = viewModel.takePhoto() + viewModel.send() + advance() + + viewModel.close() + + assertEquals(listOf(taken), photoStorage.deleted) + } + /** * Creates photos like the camera folder: "taken_0", "taken_1", … in [taken], or none while * [full]. Records the photos deleted. From e1f66d3936e2fce9a61053d44bcdd08022fbf8ae Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:07:36 +0100 Subject: [PATCH 11/21] test(chat): cover the photo button and attachment Co-Authored-By: Claude Opus 5.5 --- .../chat/ui/ConversationScreenTest.kt | 117 ++++++++++++++++++ 1 file changed, 117 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 602ac160..583b7c9c 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 @@ -109,6 +109,11 @@ class ConversationScreenTest { onSend: () -> Unit = {}, onRetry: () -> Unit = {}, onDismissSendError: () -> Unit = {}, + onTakePhoto: () -> Unit = {}, + onChoosePhoto: () -> Unit = {}, + onRemoveAttachedPhoto: () -> Unit = {}, + onRetryPhoto: (String) -> Unit = {}, + onDiscardPhoto: (String) -> Unit = {}, ) { composeTestRule.setContent { ConversationContent( @@ -118,6 +123,11 @@ class ConversationScreenTest { onSend = onSend, onRetry = onRetry, onDismissSendError = onDismissSendError, + onTakePhoto = onTakePhoto, + onChoosePhoto = onChoosePhoto, + onRemoveAttachedPhoto = onRemoveAttachedPhoto, + onRetryPhoto = onRetryPhoto, + onDiscardPhoto = onDiscardPhoto, zone = ZoneOffset.UTC, ) } @@ -835,6 +845,113 @@ class ConversationScreenTest { node(ConversationScreenTags.MESSAGE_FIELD).assert(hasDraft("Is it free on Saturday?!")) } + // Photo button and attached photo + + // A photo that cannot be read, which shows the placeholder: Robolectric throws for an unknown + // content:// URI, where a device answers FileNotFoundException. + private val galleryPhoto = Uri.parse("file:///missing/photo_1.jpg") + + /** The loaded conversation, where a photo can be attached. */ + private val canAttach = loaded.copy(canAttachPhoto = true) + + @Test + fun photoButton_isEnabledWhenAPhotoCanBeAttached_andSaysWhatItDoes() { + setContent(canAttach) + + node(ConversationScreenTags.PHOTO_BUTTON) + .assertIsEnabled() + .assertContentDescriptionEquals(string(R.string.conversation_photo_button)) + } + + @Test + fun photoButton_isDisabledWhenNoPhotoCanBeAttached() { + setContent(loaded.copy(canAttachPhoto = false)) + + node(ConversationScreenTags.PHOTO_BUTTON).assertIsNotEnabled() + } + + @Test + fun photoMenu_takePhoto_opensTheCamera_andClosesTheMenu() { + var takes = 0 + var chooses = 0 + setContent(canAttach, onTakePhoto = { takes++ }, onChoosePhoto = { chooses++ }) + node(ConversationScreenTags.TAKE_PHOTO).assertDoesNotExist() + + node(ConversationScreenTags.PHOTO_BUTTON).performClick() + node(ConversationScreenTags.TAKE_PHOTO) + .assertTextEquals(string(R.string.conversation_take_photo)) + .performClick() + + assertEquals(1, takes) + assertEquals(0, chooses) + node(ConversationScreenTags.PHOTO_MENU).assertDoesNotExist() + } + + @Test + fun photoMenu_choosePhoto_opensTheGallery_andClosesTheMenu() { + var takes = 0 + var chooses = 0 + setContent(canAttach, onTakePhoto = { takes++ }, onChoosePhoto = { chooses++ }) + + node(ConversationScreenTags.PHOTO_BUTTON).performClick() + node(ConversationScreenTags.CHOOSE_PHOTO) + .assertTextEquals(string(R.string.conversation_choose_photo)) + .performClick() + + assertEquals(0, takes) + assertEquals(1, chooses) + node(ConversationScreenTags.PHOTO_MENU).assertDoesNotExist() + } + + @Test + fun noAttachedPhoto_showsNoPreview_andTheMessagePlaceholder() { + setContent(canAttach) + + node(ConversationScreenTags.ATTACHED_PHOTO).assertDoesNotExist() + node(ConversationScreenTags.REMOVE_ATTACHED_PHOTO).assertDoesNotExist() + text(string(R.string.conversation_placeholder)).assertIsDisplayed() + } + + @Test + fun attachedPhoto_showsAboveTheField_andAsksForACaption() { + setContent(canAttach.copy(attachedPhoto = galleryPhoto)) + + node(ConversationScreenTags.ATTACHED_PHOTO) + .assertIsDisplayed() + .assertContentDescriptionEquals(string(R.string.conversation_attached_photo)) + text(string(R.string.conversation_placeholder_caption)).assertIsDisplayed() + text(string(R.string.conversation_placeholder)).assertDoesNotExist() + val photo = node(ConversationScreenTags.ATTACHED_PHOTO).getBoundsInRoot() + val field = node(ConversationScreenTags.MESSAGE_FIELD).getBoundsInRoot() + assertTrue(photo.bottom <= field.top) + } + + @Test + fun removeAttachedPhoto_callsTheCallback() { + var removals = 0 + setContent( + canAttach.copy(attachedPhoto = galleryPhoto), + onRemoveAttachedPhoto = { removals++ }, + ) + + node(ConversationScreenTags.REMOVE_ATTACHED_PHOTO) + .assertContentDescriptionEquals(string(R.string.conversation_remove_attached_photo)) + .performClick() + + assertEquals(1, removals) + } + + @Test + fun attachedPhotoWithoutACaption_canBeSent() { + var sends = 0 + setContent(canAttach.copy(attachedPhoto = galleryPhoto, canSend = true), onSend = { sends++ }) + + node(ConversationScreenTags.MESSAGE_FIELD).assert(hasDraft("")) + node(ConversationScreenTags.SEND_BUTTON).assertIsEnabled().performClick() + + assertEquals(1, sends) + } + /** No test of the screen takes a photo yet. */ private object NoPhotoStorage : PhotoStorage { override fun newPhoto(): TakenPhoto? = null From aace41c24cbb3ac2bfd14c2c1302d3e6971a9f08 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:41:38 +0100 Subject: [PATCH 12/21] test(chat): cover the photos being sent Co-Authored-By: Claude Opus 5.5 --- .../chat/ui/ConversationScreenTest.kt | 56 +++++++++++++++++++ 1 file changed, 56 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 583b7c9c..b44c3aea 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt @@ -47,6 +47,8 @@ import com.android.polybazaar.chat.model.FakeChatRepository import com.android.polybazaar.chat.viewmodel.ConversationListingStatus import com.android.polybazaar.chat.viewmodel.ConversationUiState import com.android.polybazaar.chat.viewmodel.ConversationViewModel +import com.android.polybazaar.chat.viewmodel.PendingPhoto +import com.android.polybazaar.chat.viewmodel.PendingPhotoStatus import com.android.polybazaar.error.model.AppError import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.ItemListing @@ -952,6 +954,60 @@ class ConversationScreenTest { assertEquals(1, sends) } + // Photos being sent + + private val photoTime = Instant.parse("2026-11-11T09:16:00Z") + + /** A photo message [id] from [senderUid], with [caption] as its text ("" for none). */ + private fun photoMessage(id: String, senderUid: String, caption: String = "") = + ChatMessage(id, senderUid, caption, photoTime, imagePath = "conversations/drill_renter/$id") + + private fun pending(status: PendingPhotoStatus, error: AppError? = null) = + PendingPhoto("m5", galleryPhoto, "And the shelf", status, error) + + @Test + fun uploadingPhoto_saysSending_withoutRetryOrRemove() { + setContent(loaded.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING)))) + + node(ConversationScreenTags.pendingPhoto("m5")) + .assertContentDescriptionEquals(string(R.string.conversation_photo)) + .assertTextEquals("And the shelf", string(R.string.conversation_photo_sending)) + node(ConversationScreenTags.retryPhoto("m5")).assertDoesNotExist() + node(ConversationScreenTags.discardPhoto("m5")).assertDoesNotExist() + } + + @Test + fun failedPhoto_saysWhy_andOffersRetryAndRemove() { + val retried = mutableListOf() + val discarded = mutableListOf() + setContent( + loaded.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.FAILED, AppError.NETWORK))), + onRetryPhoto = { retried += it }, + onDiscardPhoto = { discarded += it }, + ) + + text(string(R.string.conversation_photo_not_sent, string(R.string.error_network))) + .assertIsDisplayed() + .assert(isPoliteLiveRegion()) + text(string(R.string.conversation_photo_sending)).assertDoesNotExist() + node(ConversationScreenTags.retryPhoto("m5")).performClick() + node(ConversationScreenTags.discardPhoto("m5")).performClick() + + assertEquals(listOf("m5"), retried) + assertEquals(listOf("m5"), discarded) + } + + @Test + fun pendingPhotos_showBelowTheMessages_asMyOwnBubbles() { + setContent(loaded.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING)))) + + val pending = node(ConversationScreenTags.pendingPhoto("m5")).getBoundsInRoot() + val answer = node(ConversationScreenTags.theirMessage("m2")).getBoundsInRoot() + val mine = node(ConversationScreenTags.myMessage("m1")).getBoundsInRoot() + assertTrue(answer.bottom <= pending.top) + assertEquals(mine.right.value, pending.right.value, 0.5f) + } + /** No test of the screen takes a photo yet. */ private object NoPhotoStorage : PhotoStorage { override fun newPhoto(): TakenPhoto? = null From ec6b63b690e7a59a701f7e58b62ad9bee12abfc0 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:20:29 +0100 Subject: [PATCH 13/21] test(chat): cover the photo menu on the screen Co-Authored-By: Claude Opus 5.5 --- .../chat/ui/ConversationScreenTest.kt | 121 +++++++++++++++++- 1 file changed, 119 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt index b44c3aea..aaa084d4 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 @@ -1,12 +1,21 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.ui +import android.Manifest +import android.app.Application import android.content.Context import android.net.Uri +import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.result.ActivityResultRegistry +import androidx.activity.result.ActivityResultRegistryOwner +import androidx.activity.result.contract.ActivityResultContract +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf 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.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher @@ -20,6 +29,7 @@ import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.assertWidthIsEqualTo +import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasTestTag @@ -32,6 +42,7 @@ import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performTextReplacement import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp +import androidx.core.app.ActivityOptionsCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry @@ -51,11 +62,15 @@ import com.android.polybazaar.chat.viewmodel.PendingPhoto import com.android.polybazaar.chat.viewmodel.PendingPhotoStatus import com.android.polybazaar.error.model.AppError import com.android.polybazaar.listing.model.FakeListingRepository +import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.ListingCategory import com.android.polybazaar.listing.model.PhotoStorage import com.android.polybazaar.listing.model.TakenPhoto +import com.android.polybazaar.listing.ui.CreateListingScreenTags import com.android.polybazaar.profile.model.FakeProfileRepository +import com.android.polybazaar.profile.ui.redPhoto +import java.io.File import java.net.UnknownHostException import java.time.Instant import java.time.ZoneOffset @@ -66,6 +81,7 @@ import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode @@ -202,6 +218,8 @@ class ConversationScreenTest { chat: FakeChatRepository, listings: FakeListingRepository = FakeListingRepository(allListings = listOf(drill)), lifecycleOwner: LifecycleOwner? = null, + photoStorage: PhotoStorage = NoPhotoStorage, + launchers: FakeLaunchers = FakeLaunchers(), ): ConversationViewModel { val viewModel = ConversationViewModel( @@ -211,11 +229,17 @@ class ConversationScreenTest { chatRepository = chat, profileRepository = FakeProfileRepository(mapOf(james.uid to james)), listingRepository = listings, - photoStorage = NoPhotoStorage, + photoStorage = photoStorage, ) + val launcherOwner = + object : ActivityResultRegistryOwner { + override val activityResultRegistry = launchers + } composeTestRule.setContent { CompositionLocalProvider( - LocalLifecycleOwner provides (lifecycleOwner ?: LocalLifecycleOwner.current) + LocalLifecycleOwner provides (lifecycleOwner ?: LocalLifecycleOwner.current), + // rememberLauncherForActivityResult reads its registry from this composition local. + LocalActivityResultRegistryOwner provides launcherOwner, ) { ConversationScreen(viewModel = viewModel, onBack = {}) } @@ -223,6 +247,26 @@ class ConversationScreenTest { return viewModel } + /** + * Stands in for the gallery, the camera app and the permission request: answers each launch at + * once with the next of [results] (a picked URI or null, or a Boolean for the camera and the + * permission), and records each contract launched in [launched]. + */ + private class FakeLaunchers : ActivityResultRegistry() { + val results = ArrayDeque() + val launched = mutableListOf>() + + override fun onLaunch( + requestCode: Int, + contract: ActivityResultContract, + input: I, + options: ActivityOptionsCompat?, + ) { + launched += contract + dispatchResult(requestCode, results.removeFirst()) + } + } + /** A lifecycle a test moves by hand, to put the screen in the background and back. */ private class ManualLifecycleOwner : LifecycleOwner { val registry = @@ -1008,6 +1052,79 @@ class ConversationScreenTest { assertEquals(mine.right.value, pending.right.value, 0.5f) } + // The screen wires the photo menu to the gallery, the camera and the ViewModel. + + /** A chat whose conversation exists, so a photo can be attached. */ + private fun existingConversation() = FakeChatRepository(listOf(conversation)) + + private fun openPhotoMenuAndPick(tag: String) { + node(ConversationScreenTags.PHOTO_BUTTON).assertIsEnabled().performClick() + node(tag).performClick() + } + + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) // Real decoding and drawing of the thumbnail. + fun screen_choosingFromTheGallery_attachesThePickedPhoto_andShowsIt() { + val picked = File(context.cacheDir, "picked.png").apply { writeBytes(redPhoto()) } + val launchers = FakeLaunchers().apply { results.add(Uri.fromFile(picked)) } + val viewModel = showScreen(existingConversation(), launchers = launchers) + + openPhotoMenuAndPick(ConversationScreenTags.CHOOSE_PHOTO) + + assertTrue(launchers.launched.single() is ActivityResultContracts.PickVisualMedia) + assertEquals(Uri.fromFile(picked), viewModel.uiState.value.attachedPhoto) + composeTestRule.waitUntil(5_000) { + val image = + composeTestRule + .onNodeWithTag(ConversationScreenTags.ATTACHED_PHOTO, useUnmergedTree = true) + .captureToImage() + image.toPixelMap()[image.width / 2, image.height / 2] == Color.Red + } + } + + @Test + fun screen_closingTheGalleryWithoutAPhoto_attachesNothing() { + val launchers = FakeLaunchers().apply { results.add(null) } + val viewModel = showScreen(existingConversation(), launchers = launchers) + + openPhotoMenuAndPick(ConversationScreenTags.CHOOSE_PHOTO) + + assertEquals(null, viewModel.uiState.value.attachedPhoto) + node(ConversationScreenTags.ATTACHED_PHOTO).assertDoesNotExist() + } + + // The camera app leaves its file empty; native graphics fail to decode it cleanly. + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) + fun screen_takingAPhoto_withPermission_attachesTheTakenFile() { + shadowOf(context as Application).grantPermissions(Manifest.permission.CAMERA) + val launchers = FakeLaunchers().apply { results.add(true) } // The camera app saved it. + val storage = FilePhotoStorage(context, FilePhotoStorage.CHAT_FORM) + val viewModel = + showScreen(existingConversation(), photoStorage = storage, launchers = launchers) + + openPhotoMenuAndPick(ConversationScreenTags.TAKE_PHOTO) + + assertTrue(launchers.launched.single() is ActivityResultContracts.TakePicture) + val attached = viewModel.uiState.value.attachedPhoto + assertTrue(attached != null && File(attached.path!!).exists()) + node(ConversationScreenTags.ATTACHED_PHOTO).assertIsDisplayed() + } + + @Test + fun screen_refusingTheCamera_explainsWhy_andCancelClosesIt() { + val launchers = FakeLaunchers().apply { results.add(false) } // The user refuses. + val viewModel = showScreen(existingConversation(), launchers = launchers) + + openPhotoMenuAndPick(ConversationScreenTags.TAKE_PHOTO) + + assertTrue(launchers.launched.single() is ActivityResultContracts.RequestPermission) + node(CreateListingScreenTags.CAMERA_PERMISSION_DIALOG).assertIsDisplayed() + node(CreateListingScreenTags.CAMERA_PERMISSION_CANCEL).performClick() + node(CreateListingScreenTags.CAMERA_PERMISSION_DIALOG).assertDoesNotExist() + assertEquals(null, viewModel.uiState.value.attachedPhoto) + } + /** No test of the screen takes a photo yet. */ private object NoPhotoStorage : PhotoStorage { override fun newPhoto(): TakenPhoto? = null From 41bc999f2f8d924acfa3526881ff028d649f638d Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 03:28:27 +0100 Subject: [PATCH 14/21] fix(chat): show a photo once while it is being sent Its message is written before the photo is uploaded, so it showed next to the pending bubble. Messages with a pending photo are now left out until the photo is sent. Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 2 +- .../chat/viewmodel/ConversationViewModel.kt | 16 +++++++++++++-- .../chat/ui/ConversationScreenTest.kt | 13 ++++++++++++ .../viewmodel/ConversationViewModelTest.kt | 20 +++++++++++++++++++ 4 files changed, 48 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 4f385ba1..49581c2c 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 @@ -520,7 +520,7 @@ private fun MessageList( onRetry: () -> Unit, photoActions: PhotoActions, ) { - val messages = uiState.messages + val messages = uiState.shownMessages val pendingPhotos = uiState.pendingPhotos val listState = rememberLazyListState() // The list keeps its place by key, so a new message or photo would arrive below the view without 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 f8c6b70d..082b808c 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 @@ -77,7 +77,8 @@ data class PendingPhoto( * @property firstMessageBlockedByPause true when the renter has no conversation yet and the listing * is paused: the rules refuse a first message until it is active again. False while the * conversation loads and after it failed to load, when whether it exists is unknown. - * @property pendingPhotos the photos sent that are not in [messages] yet, oldest first. + * @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 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,7 +101,18 @@ data class ConversationUiState( val isLoading: Boolean = true, val loadError: AppError? = null, val sendError: AppError? = null, -) +) { + /** + * The [messages] to show: those of [pendingPhotos] are left out, as their pending bubble already + * shows them, so a photo shows once while it uploads or after it failed. + */ + val shownMessages: List = + if (pendingPhotos.isEmpty()) messages + else { + val pendingIds = pendingPhotos.mapTo(HashSet()) { it.messageId } + messages.filterNot { it.id in pendingIds } + } +} /** The listing as last observed, kept in one reference so other threads never see half of it. */ private data class LoadedListing( 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 aaa084d4..1779c5ce 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 @@ -1009,6 +1009,19 @@ class ConversationScreenTest { private fun pending(status: PendingPhotoStatus, error: AppError? = null) = PendingPhoto("m5", galleryPhoto, "And the shelf", status, error) + @Test + fun pendingPhoto_whoseMessageArrived_showsOnce() { + setContent( + loaded.copy( + messages = loaded.messages + photoMessage("m5", "renter", caption = "And the shelf"), + pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING)), + ) + ) + + node(ConversationScreenTags.pendingPhoto("m5")).assertIsDisplayed() + node(ConversationScreenTags.myMessage("m5")).assertDoesNotExist() + } + @Test fun uploadingPhoto_saysSending_withoutRetryOrRemove() { setContent(loaded.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING)))) 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 ba198a89..a5a8c1b9 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 @@ -1303,6 +1303,26 @@ class ConversationViewModelTest { assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) } + @Test + fun sendPhoto_hidesItsMessageUntilSent_soThePhotoShowsOnce() { + val viewModel = inConversation() + val sent = ChatMessage("m1", renter.uid, "", Instant.ofEpochSecond(300), imagePath = "chats/m1") + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + + // The message reaches the conversation before its photo is uploaded. + chat.messages.value = mapOf(conversation.id to listOf(sent)) + advance() + assertEquals(listOf(sent), viewModel.uiState.value.messages) + assertEquals(emptyList(), viewModel.uiState.value.shownMessages) + + chat.gate!!.complete(Unit) + advance() + assertEquals(listOf(sent), viewModel.uiState.value.shownMessages) + } + @Test fun sendPhoto_tappedTwice_sendsOnce() { val viewModel = inConversation() From b9ba7e9ca53d572962bec210bf18c33383b438db Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 17:03:59 +0100 Subject: [PATCH 15/21] fix(chat): rely on the listing observation after a photo fails Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/viewmodel/ConversationViewModel.kt | 6 +++--- .../polybazaar/chat/viewmodel/ConversationViewModelTest.kt | 6 ++---- 2 files changed, 5 insertions(+), 7 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 082b808c..4313caff 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 @@ -328,9 +328,9 @@ class ConversationViewModel( deleteIfTaken(pending.photo) } catch (exception: Exception) { if (exception is CancellationException) throw exception - val error = exception.toAppError() - _uiState.update { it.withPendingPhoto(pending.failed(error)) } - reloadListingAfter(error) + // A refusal from a pause or deletion of the listing also reaches its observation, which + // then stops new photos from being attached. + _uiState.update { it.withPendingPhoto(pending.failed(exception.toAppError())) } } } } 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 a5a8c1b9..4e954ff8 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 @@ -1427,21 +1427,19 @@ class ConversationViewModelTest { viewModel.uiState.value.pendingPhotos, ) assertNull(viewModel.uiState.value.sendError) - assertEquals(1, listings.getListingCalls) } @Test - fun sendPhoto_refused_failsWithPermissionDenied_andReloadsTheListing() { + fun sendPhoto_refused_failsWithPermissionDenied() { val viewModel = failedPhotoSend(refused) val pending = viewModel.uiState.value.pendingPhotos.single() assertEquals(PendingPhotoStatus.FAILED, pending.status) assertEquals(AppError.PERMISSION_DENIED, pending.error) - assertEquals(2, listings.getListingCalls) } @Test - fun sendPhoto_toADeletedListing_reloadsItAndStopsAttachingPhotos() { + fun sendPhoto_toADeletedListing_failsAndTheDeletionStopsAttachingPhotos() { val viewModel = inConversation() listings.allListings = emptyList() chat.sendFailure = firestoreError(FirebaseFirestoreException.Code.NOT_FOUND) From 5604777c9e80438829daf6cbe2dcec224d125e9f Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 18:29:35 +0100 Subject: [PATCH 16/21] fix(chat): don't send a photo while a text is still being sent Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 5 ++-- .../viewmodel/ConversationViewModelTest.kt | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 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 4313caff..d5406f08 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 @@ -239,13 +239,14 @@ class ConversationViewModel( */ fun send() { val state = _uiState.value - if (!state.canSend) return + // Also for a photo: until the text sent before returns, the draft still holds it, and the photo + // would send it again as its caption. + if (!state.canSend || sendInFlight) return val photo = state.attachedPhoto if (photo != null) { sendPhoto(state, photo) return } - if (sendInFlight) return // Before the conversation has loaded, a renter's message is sent as a first one: the merge // write becomes an update when the conversation exists, and the rules accept it. val target = state.conversation ?: firstConversation() ?: return 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 4e954ff8..1115b7d0 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 @@ -1025,6 +1025,31 @@ class ConversationViewModelTest { assertTrue(viewModel.uiState.value.canSend) } + @Test + fun send_aPhotoWhileATextSendIsInFlight_doesNothing_soTheTextIsNotSentAgainAsItsCaption() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.onDraftChange("Hello") + viewModel.send() + advance() + + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + assertEquals(emptyList(), chat.sentPhotos) + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + + chat.gate!!.complete(Unit) + advance() + viewModel.send() + advance() + assertEquals( + listOf(FakeChatRepository.SentPhoto(conversation, "m1", galleryPhoto, null)), + chat.sentPhotos, + ) + assertEquals(listOf(conversation to "Hello"), chat.sentMessages) + } + @Test fun attachPhoto_beforeTheConversationExists_isIgnored() { val viewModel = loadedViewModel() From eade3dc5ee5d1eb01368fcc628e51ad4785a445a Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 18:31:36 +0100 Subject: [PATCH 17/21] fix(chat): keep a photo picked or taken while the conversation loads Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 18 +++++++-- .../viewmodel/ConversationViewModelTest.kt | 37 ++++++++++++++++++- 2 files changed, 50 insertions(+), 5 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 d5406f08..80eb85e0 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 @@ -188,10 +188,11 @@ class ConversationViewModel( /** * Attaches [photo], picked from the gallery, replacing the photo attached before. Ignored when a - * photo cannot be attached. + * photo cannot be attached; while the screen is still loading, it is attached and can be sent + * once the conversation is known to allow it. */ fun attachPhoto(photo: Uri) { - if (!_uiState.value.canAttachPhoto) return + if (!_uiState.value.mayReceivePhoto()) return replaceAttachedPhoto(photo) } @@ -212,12 +213,13 @@ class ConversationViewModel( /** * Attaches the photo the camera app took, or deletes its empty file if [saved] is false or a - * photo can no longer be attached. + * photo can no longer be attached. While the screen is still loading, it is attached as in + * [attachPhoto]. */ fun finishTakingPhoto(saved: Boolean) { val photo = photoBeingTaken ?: return photoBeingTaken = null - if (!saved || !_uiState.value.canAttachPhoto) { + if (!saved || !_uiState.value.mayReceivePhoto()) { photoStorage.delete(photo) return } @@ -385,6 +387,14 @@ class ConversationViewModel( if (replaced != null && replaced != photo) deleteIfTaken(replaced) } + /** + * Whether a photo picked or taken can be attached: when it can be, and also while the screen is + * loading, as when it was just recreated and the result arrives before the conversation. Then + * [ConversationUiState.canSend] waits for the conversation to allow it. + */ + private fun ConversationUiState.mayReceivePhoto(): Boolean = + canAttachPhoto || (isLoading && listingStatus != ConversationListingStatus.DELETED) + private fun ConversationUiState.failedPhoto(messageId: String): PendingPhoto? = pendingPhotos.find { it.messageId == messageId && it.status == PendingPhotoStatus.FAILED 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 1115b7d0..d674fc3d 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 @@ -1073,13 +1073,48 @@ class ConversationViewModelTest { } @Test - fun attachPhoto_whileTheListingIsUnknown_isIgnored() { + fun attachPhoto_whileTheScreenLoads_attachesIt_andItCanBeSentOnceTheConversationIsKnown() { listings.gate = CompletableDeferred() val viewModel = inConversation() + assertTrue(viewModel.uiState.value.isLoading) viewModel.attachPhoto(galleryPhoto) + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + assertFalse(viewModel.uiState.value.canSend) + + listings.gate!!.complete(Unit) + advance() + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + assertTrue(viewModel.uiState.value.canSend) + } + + @Test + fun attachPhoto_whileTheScreenLoads_staysUnsendableWhenTheConversationTurnsOutMissing() { + chat.conversationGate = CompletableDeferred() + val viewModel = loadedViewModel() + assertTrue(viewModel.uiState.value.isLoading) + viewModel.attachPhoto(galleryPhoto) + chat.conversationGate!!.complete(Unit) + advance() + + assertFalse(viewModel.uiState.value.isLoading) assertFalse(viewModel.uiState.value.canAttachPhoto) + assertFalse(viewModel.uiState.value.canSend) + // Still shown, so the user can remove it. + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + } + + @Test + fun attachPhoto_whileTheScreenLoads_toADeletedListing_isIgnored() { + listings.allListings = emptyList() + chat.conversationGate = CompletableDeferred() + val viewModel = loadedViewModel() + assertTrue(viewModel.uiState.value.isLoading) + assertEquals(ConversationListingStatus.DELETED, viewModel.uiState.value.listingStatus) + + viewModel.attachPhoto(galleryPhoto) + assertNull(viewModel.uiState.value.attachedPhoto) } From 6b012ac76ec036b0a2a914b7d206740318bc61df Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 18:33:28 +0100 Subject: [PATCH 18/21] fix(chat): keep the photo being taken when Android kills the app Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/ui/ConversationScreen.kt | 3 +- .../chat/viewmodel/ConversationViewModel.kt | 20 +++++++- .../polybazaar/ui/navigation/AppNavHost.kt | 1 + .../chat/ui/ConversationScreenTest.kt | 2 + .../viewmodel/ConversationViewModelTest.kt | 47 ++++++++++++++++++- 5 files changed, 68 insertions(+), 5 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 49581c2c..3efe6947 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 @@ -192,7 +192,8 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> if (uri != null) viewModel.attachPhoto(uri) } - // The ViewModel keeps the photo file, so it survives the activity being recreated meanwhile. + // The ViewModel keeps the photo file in its saved state, so it survives the activity being + // recreated meanwhile, and Android killing the app while the camera app is in front. val camera = rememberPhotoCamera( startTakingPhoto = { _ -> viewModel.startTakingPhoto() }, 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 80eb85e0..1160ef19 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 @@ -2,6 +2,7 @@ package com.android.polybazaar.chat.viewmodel import android.net.Uri +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.polybazaar.auth.model.User @@ -127,6 +128,10 @@ private data class LoadedListing( * [photoStorage] keeps the photos taken with the camera until they are sent; photos picked from the * gallery belong to the user and are never deleted. * + * [savedStateHandle] keeps the photo the camera app is taking when Android kills the app, which can + * happen while the camera app is in front. Pass `createSavedStateHandle()` from the factory: a + * handle made by hand is not saved by Android. + * * The lender must only be routed here for a conversation that already exists: until then the * security rules refuse them the conversation and its messages, which shows as a load error. */ @@ -138,6 +143,7 @@ class ConversationViewModel( private val profileRepository: ProfileRepository, private val listingRepository: ListingRepository, private val photoStorage: PhotoStorage, + private val savedStateHandle: SavedStateHandle, ) : ViewModel() { private val _uiState = MutableStateFlow(ConversationUiState(myUid = myUid)) @@ -160,8 +166,14 @@ class ConversationViewModel( private var sendInFlight = false private var lastMarkedReadAt: Instant? = null private var isVisible = false - // The photo the camera app is taking, until it closes. - private var photoBeingTaken: Uri? = null + // The photo the camera app is taking, until it closes. Saved, so that it is still attached when + // the camera app returns to an app that Android killed meanwhile. + private var photoBeingTaken: Uri? + get() = savedStateHandle[PHOTO_BEING_TAKEN] + set(value) { + savedStateHandle[PHOTO_BEING_TAKEN] = value + } + // Photos taken with the camera and not deleted yet, so gallery photos are never deleted. private val takenPhotos = mutableSetOf() @@ -622,4 +634,8 @@ class ConversationViewModel( conversationKnown, ) } + + private companion object { + const val PHOTO_BEING_TAKEN = "photoBeingTaken" + } } diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index 127a7d99..5d6e5bff 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -466,6 +466,7 @@ fun AppNavHost( profileRepository = profileRepository, listingRepository = listingRepository, photoStorage = chatPhotoStorage, + savedStateHandle = createSavedStateHandle(), ) } } 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 1779c5ce..87a4384b 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 @@ -46,6 +46,7 @@ import androidx.core.app.ActivityOptionsCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 @@ -230,6 +231,7 @@ class ConversationScreenTest { profileRepository = FakeProfileRepository(mapOf(james.uid to james)), listingRepository = listings, photoStorage = photoStorage, + savedStateHandle = SavedStateHandle(), ) val launcherOwner = object : ActivityResultRegistryOwner { 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 d674fc3d..80ad2a38 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 @@ -2,6 +2,7 @@ package com.android.polybazaar.chat.viewmodel import android.net.Uri +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStore import androidx.lifecycle.viewmodel.initializer @@ -91,8 +92,14 @@ class ConversationViewModelTest { private fun advance() = testDispatcher.scheduler.advanceUntilIdle() - /** Creates the ViewModel for the drill conversation, seen by [myUid], without running it. */ - private fun viewModel(myUid: String = renter.uid) = + /** + * Creates the ViewModel for the drill conversation, seen by [myUid], without running it. + * [savedState] is what Android restores after it killed the app. + */ + private fun viewModel( + myUid: String = renter.uid, + savedState: SavedStateHandle = SavedStateHandle(), + ) = ConversationViewModel( listing.listingId!!, renter.uid, @@ -101,6 +108,7 @@ class ConversationViewModelTest { profiles, listings, photoStorage, + savedState, ) /** Creates the ViewModel and lets its loads finish. */ @@ -1131,6 +1139,41 @@ class ConversationViewModelTest { assertEquals(emptyList(), photoStorage.deleted) } + /** The state Android saves for this ViewModel, as restored into a new process. */ + private fun SavedStateHandle.restored() = SavedStateHandle(keys().associateWith { get(it) }) + + @Test + fun takePhoto_afterAndroidKilledTheApp_attachesItToTheNewViewModel() { + val savedState = SavedStateHandle() + givenConversation() + viewModel(savedState = savedState).also { advance() }.startTakingPhoto() + val taken = photoStorage.taken.single().uri + + // The camera result reaches the new process before the conversation has loaded again. + val restarted = viewModel(savedState = savedState.restored()) + restarted.finishTakingPhoto(saved = true) + advance() + + assertEquals(taken, restarted.uiState.value.attachedPhoto) + assertTrue(restarted.uiState.value.canSend) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun takePhoto_cancelledAfterAndroidKilledTheApp_deletesTheFile() { + val savedState = SavedStateHandle() + givenConversation() + viewModel(savedState = savedState).also { advance() }.startTakingPhoto() + val taken = photoStorage.taken.single().uri + + val restarted = viewModel(savedState = savedState.restored()) + restarted.finishTakingPhoto(saved = false) + advance() + + assertNull(restarted.uiState.value.attachedPhoto) + assertEquals(listOf(taken), photoStorage.deleted) + } + @Test fun takePhoto_cancelled_deletesTheFile_andAttachesNothing() { val viewModel = inConversation() From 0e5bdb02a1635d8d76641585796f0ed5aa6ecaf6 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 18:36:07 +0100 Subject: [PATCH 19/21] fix(chat): let a photo upload finish after leaving the conversation Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 26 +++++++--- .../chat/viewmodel/PhotoUploadScope.kt | 13 +++++ .../polybazaar/ui/navigation/AppNavHost.kt | 2 + .../chat/ui/ConversationScreenTest.kt | 4 ++ .../viewmodel/ConversationViewModelTest.kt | 49 +++++++++++++++++-- 5 files changed, 84 insertions(+), 10 deletions(-) create mode 100644 app/src/main/java/com/android/polybazaar/chat/viewmodel/PhotoUploadScope.kt 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 1160ef19..2264adc2 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 @@ -21,6 +21,7 @@ import com.android.polybazaar.profile.model.ProfileRepository import java.time.Instant import java.util.concurrent.atomic.AtomicBoolean import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -132,6 +133,10 @@ private data class LoadedListing( * happen while the camera app is in front. Pass `createSavedStateHandle()` from the factory: a * handle made by hand is not saved by Android. * + * [uploadScope] runs the photo uploads, so that closing the screen does not cancel them: pass + * [photoUploadScope]. Once the screen is closed, an upload that ends deletes its photo if it was + * taken with the camera, whether it was sent or not, as nothing can retry it any more. + * * The lender must only be routed here for a conversation that already exists: until then the * security rules refuse them the conversation and its messages, which shows as a load error. */ @@ -144,6 +149,7 @@ class ConversationViewModel( private val listingRepository: ListingRepository, private val photoStorage: PhotoStorage, private val savedStateHandle: SavedStateHandle, + private val uploadScope: CoroutineScope, ) : ViewModel() { private val _uiState = MutableStateFlow(ConversationUiState(myUid = myUid)) @@ -166,6 +172,8 @@ class ConversationViewModel( private var sendInFlight = false private var lastMarkedReadAt: Instant? = null private var isVisible = false + // Whether the screen is closed, so an upload that fails afterwards deletes its photo. + private var cleared = false // The photo the camera app is taking, until it closes. Saved, so that it is still attached when // the camera app returns to an app that Android killed meanwhile. private var photoBeingTaken: Uri? @@ -333,7 +341,7 @@ class ConversationViewModel( * Sends [pending], then removes it once the server has its message and photo, or marks it failed. */ private fun upload(conversation: Conversation, pending: PendingPhoto) { - viewModelScope.launch { + uploadScope.launch { try { chatRepository.sendPhoto(conversation, pending.messageId, pending.photo, pending.caption) _uiState.update { @@ -346,6 +354,8 @@ class ConversationViewModel( // A refusal from a pause or deletion of the listing also reaches its observation, which // then stops new photos from being attached. _uiState.update { it.withPendingPhoto(pending.failed(exception.toAppError())) } + // Closed: no one can retry it. + if (cleared) deleteIfTaken(pending.photo) } } } @@ -382,15 +392,17 @@ class ConversationViewModel( /** * Deletes the photos taken with the camera that were not sent: the one being taken, the attached - * one and the failed ones. Gallery photos are left alone. + * one and the failed ones. Gallery photos are left alone. The uploads under way keep running in + * [uploadScope] and delete their photo when they end. */ override fun onCleared() { + cleared = true photoBeingTaken?.let(photoStorage::delete) - // Closing the screen cancels the uploads under way, but compressing a photo is not cancelled - // mid-read, so their files are kept rather than deleted under it. They stay in the chat folder. - if (_uiState.value.pendingPhotos.any { it.status == PendingPhotoStatus.UPLOADING }) return - takenPhotos.forEach(photoStorage::delete) - takenPhotos.clear() + val uploading = + _uiState.value.pendingPhotos + .filter { it.status == PendingPhotoStatus.UPLOADING } + .mapTo(HashSet()) { it.photo } + takenPhotos.filterNot { it in uploading }.forEach(::deleteIfTaken) } private fun replaceAttachedPhoto(photo: Uri) { diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/PhotoUploadScope.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/PhotoUploadScope.kt new file mode 100644 index 00000000..1ee54706 --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/PhotoUploadScope.kt @@ -0,0 +1,13 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.chat.viewmodel + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob + +/** + * Runs the photo uploads of [ConversationViewModel] for as long as the app's process lives, so that + * leaving a conversation does not cancel an upload after its message is written, which would leave + * the photo pending for both participants. On the main thread, like viewModelScope. + */ +val photoUploadScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index 5d6e5bff..ff23ea63 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -68,6 +68,7 @@ import com.android.polybazaar.chat.ui.ConversationScreen import com.android.polybazaar.chat.ui.InboxScreen import com.android.polybazaar.chat.viewmodel.ConversationViewModel import com.android.polybazaar.chat.viewmodel.InboxViewModel +import com.android.polybazaar.chat.viewmodel.photoUploadScope import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message import com.android.polybazaar.listing.model.FilePhotoStorage @@ -467,6 +468,7 @@ fun AppNavHost( listingRepository = listingRepository, photoStorage = chatPhotoStorage, savedStateHandle = createSavedStateHandle(), + uploadScope = photoUploadScope, ) } } 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 87a4384b..62dfbec5 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 @@ -76,6 +76,9 @@ import java.net.UnknownHostException import java.time.Instant import java.time.ZoneOffset import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue @@ -232,6 +235,7 @@ class ConversationScreenTest { listingRepository = listings, photoStorage = photoStorage, savedStateHandle = SavedStateHandle(), + uploadScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate), ) val launcherOwner = object : ActivityResultRegistryOwner { 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 80ad2a38..e6a32dd8 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,8 +25,10 @@ import com.google.firebase.firestore.FirebaseFirestoreException import java.net.UnknownHostException import java.time.Instant import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @@ -45,6 +47,8 @@ import org.junit.runner.RunWith class ConversationViewModelTest { private val testDispatcher = StandardTestDispatcher() + // Outlives the ViewModels, like photoUploadScope. + private val uploadScope = CoroutineScope(SupervisorJob() + testDispatcher) private lateinit var chat: FakeChatRepository private lateinit var profiles: FakeProfileRepository private lateinit var listings: FakeListingRepository @@ -109,6 +113,7 @@ class ConversationViewModelTest { listings, photoStorage, savedState, + uploadScope, ) /** Creates the ViewModel and lets its loads finish. */ @@ -1495,16 +1500,54 @@ class ConversationViewModelTest { } @Test - fun closing_whileAPhotoUploads_keepsTheTakenPhotos() { + fun closing_whileAPhotoUploads_letsItFinish_thenDeletesItsPhoto() { val viewModel = inConversation() chat.gate = CompletableDeferred() - viewModel.takePhoto() + val sending = viewModel.takePhoto() viewModel.send() advance() - viewModel.takePhoto() + val attached = viewModel.takePhoto() viewModel.close() + // The attached photo is deleted at once; the one uploading is still being read. + assertEquals(listOf(attached), photoStorage.deleted) + chat.gate!!.complete(Unit) + advance() + assertEquals(1, chat.sentPhotos.size) + assertEquals(listOf(attached, sending), photoStorage.deleted) + } + + @Test + fun closing_whileAPhotoUploads_deletesItsPhotoWhenItFails() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + val sending = viewModel.takePhoto() + viewModel.send() + advance() + + viewModel.close() + assertEquals(emptyList(), photoStorage.deleted) + + chat.sendFailure = offline + chat.gate!!.complete(Unit) + advance() + assertEquals(listOf(sending), photoStorage.deleted) + } + + @Test + fun closing_whileAGalleryPhotoUploads_neverDeletesIt() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + + viewModel.close() + chat.gate!!.complete(Unit) + advance() + + assertEquals(1, chat.sentPhotos.size) assertEquals(emptyList(), photoStorage.deleted) } From f7f67ae314bf2cd600c1022ff3e418daf0b56572 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 18:43:50 +0100 Subject: [PATCH 20/21] fix(chat): delete the message of a photo removed after a failed send Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/ChatRepository.kt | 10 ++++++ .../chat/model/FirebaseChatRepository.kt | 9 +++++ .../chat/viewmodel/ConversationViewModel.kt | 7 ++-- .../chat/model/FakeChatRepository.kt | 13 ++++++- .../chat/model/FirebaseChatRepositoryTest.kt | 34 +++++++++++++++++++ .../viewmodel/ConversationViewModelTest.kt | 25 ++++++++++++++ firestore.rules | 7 +++- rules-tests/firestore.test.js | 31 ++++++++++++++++- 8 files changed, 131 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt b/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt index c5733f31..6074b443 100644 --- a/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt +++ b/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt @@ -63,6 +63,16 @@ interface ChatRepository { caption: String? = null, ) + /** + * Deletes the signed-in user's photo message with this ID, for a [sendPhoto] that failed and that + * they no longer want sent, so that it does not stay pending for the other participant. Like + * [markRead], the delete is queued without waiting for the server, so it works offline, and it + * never throws: a failure is only logged. The rules only let the sender delete a message whose + * photo is still pending, and refuse to delete one that was never written, which is then only + * logged. The conversation's preview of it stays until the next message. + */ + fun deletePhotoMessage(conversationId: String, messageId: String) + /** * Downloads the photo of a message, from its [ChatMessage.imagePath], as the signed-in user. * Fails with PERMISSION_DENIED for a user who is not a participant of the conversation, with an diff --git a/app/src/main/java/com/android/polybazaar/chat/model/FirebaseChatRepository.kt b/app/src/main/java/com/android/polybazaar/chat/model/FirebaseChatRepository.kt index ae6e09a2..6049bfeb 100644 --- a/app/src/main/java/com/android/polybazaar/chat/model/FirebaseChatRepository.kt +++ b/app/src/main/java/com/android/polybazaar/chat/model/FirebaseChatRepository.kt @@ -161,6 +161,15 @@ class FirebaseChatRepository( storage.reference.child(imagePath).getBytes(PhotoStorage.MAX_PHOTO_BYTES).await() } + override fun deletePhotoMessage(conversationId: String, messageId: String) { + // Not awaited, like markRead: the delete is queued offline and the listener sees it at once. + conversationDocument(conversationId) + .collection(MESSAGES) + .document(messageId) + .delete() + .addOnFailureListener(Executor { it.run() }) { logWriteFailure(it) } + } + override fun markRead(conversationId: String) { val uid = auth.currentUser?.uid ?: return // Not awaited, like sendMessage: the write is queued offline and the listener sees it at once. 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 2264adc2..7bfb3245 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 @@ -375,14 +375,17 @@ class ConversationViewModel( } /** - * Removes the failed photo of [messageId], deleting it if it was taken with the camera. Ignored - * unless it failed: an upload under way cannot be taken back. + * Removes the failed photo of [messageId], deleting it if it was taken with the camera, and + * deletes its message, which may already be on the server with its photo pending, so the other + * participant no longer sees it. Ignored unless it failed: an upload under way cannot be taken + * back. */ fun discardPhoto(messageId: String) { val failed = _uiState.value.failedPhoto(messageId) ?: return _uiState.update { it.copy(pendingPhotos = it.pendingPhotos.filterNot { p -> p.isSameAs(failed) }) } + chatRepository.deletePhotoMessage(conversationId(listingId, renterUid), messageId) deleteIfTaken(failed.photo) } diff --git a/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt index a84845c0..6bbb1cb8 100644 --- a/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt +++ b/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt @@ -28,7 +28,8 @@ import kotlinx.coroutines.flow.map * * [sendPhoto] records every call in [sentPhotos], then waits for [gate] and throws [sendFailure] * like [sendMessage]; it has no later rejection, since a photo send waits for the server. - * [newMessageId] returns "m1", "m2", … in call order. + * [newMessageId] returns "m1", "m2", … in call order. [deletePhotoMessage] records every call in + * [deletedPhotoMessages] and removes the message from [messages]. * * [loadMessagePhoto] returns the bytes stored in [photos] for the path, and throws * [photoLoadFailure] if set, or when the path is not in [photos]. @@ -66,6 +67,9 @@ class FakeChatRepository( /** The calls to [sendPhoto], in order. */ val sentPhotos = mutableListOf() + /** The calls to [deletePhotoMessage], as (conversation id, message id), in order. */ + val deletedPhotoMessages = mutableListOf>() + /** The photos [loadMessagePhoto] returns, by Storage path. */ val photos = mutableMapOf() @@ -112,6 +116,13 @@ class FakeChatRepository( sendFailure?.let { throw it } } + override fun deletePhotoMessage(conversationId: String, messageId: String) { + deletedPhotoMessages += conversationId to messageId + val conversationMessages = messages.value[conversationId] ?: return + messages.value = + messages.value + (conversationId to conversationMessages.filterNot { it.id == messageId }) + } + override suspend fun loadMessagePhoto(imagePath: String): ByteArray { photoLoadFailure?.let { throw it } return photos[imagePath] ?: throw NoSuchElementException("No photo at $imagePath") diff --git a/app/src/test/java/com/android/polybazaar/chat/model/FirebaseChatRepositoryTest.kt b/app/src/test/java/com/android/polybazaar/chat/model/FirebaseChatRepositoryTest.kt index 593eb03f..bbe5a7ca 100644 --- a/app/src/test/java/com/android/polybazaar/chat/model/FirebaseChatRepositoryTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/model/FirebaseChatRepositoryTest.kt @@ -1049,6 +1049,40 @@ class FirebaseChatRepositoryTest { assertEquals(5_000L, testScheduler.currentTime) } + @Test + fun deletePhotoMessageDeletesTheMessageWithoutWaitingForTheServer() { + val pendingDelete = TaskCompletionSource() + whenever(photoMessageRef.delete()).thenReturn(pendingDelete.task) + var reportedFailure: Exception? = null + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } + + repository.deletePhotoMessage("listing_renter", PHOTO_ID) + + verify(photoMessageRef).delete() + assertFalse(pendingDelete.task.isComplete) + assertNull(reportedFailure) + } + + @Test + fun deletePhotoMessageLogsALaterRefusal() { + val pendingDelete = TaskCompletionSource() + whenever(photoMessageRef.delete()).thenReturn(pendingDelete.task) + var reportedFailure: Exception? = null + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } + + repository.deletePhotoMessage("listing_renter", PHOTO_ID) + val refused = + FirebaseFirestoreException( + "Missing or insufficient permissions", + FirebaseFirestoreException.Code.PERMISSION_DENIED, + ) + pendingDelete.setException(refused) + + assertSame(refused, reportedFailure) + } + @Test fun markReadSetsOnlyMyReadTimeToServerTime() { whenever(conversationRef.update(any(), any(), anyVararg())) 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 e6a32dd8..3b2474ca 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 @@ -1680,6 +1680,30 @@ class ConversationViewModelTest { assertEquals(emptyList(), photoStorage.deleted) } + @Test + fun discardPhoto_deletesItsMessage_soTheOtherParticipantNoLongerSeesIt() { + val viewModel = failedPhotoSend(refused) + // The message was written before the upload failed. + val written = + ChatMessage( + "m1", + renter.uid, + "", + Instant.ofEpochSecond(300), + imagePath = "conversations/${conversation.id}/m1.jpg", + photoPending = true, + ) + chat.messages.value = mapOf(conversation.id to listOf(hi, written)) + advance() + + viewModel.discardPhoto("m1") + advance() + + assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) + assertEquals(listOf(hi), viewModel.uiState.value.messages) + assertEquals(listOf(hi), viewModel.uiState.value.shownMessages) + } + @Test fun discardPhoto_whileItUploads_isIgnored() { val viewModel = inConversation() @@ -1694,6 +1718,7 @@ class ConversationViewModelTest { listOf(PendingPhotoStatus.UPLOADING), viewModel.uiState.value.pendingPhotos.map { it.status }, ) + assertEquals(emptyList>(), chat.deletedPhotoMessages) } @Test diff --git a/firestore.rules b/firestore.rules index 0d238c9d..853ed2e5 100644 --- a/firestore.rules +++ b/firestore.rules @@ -278,7 +278,12 @@ service cloud.firestore { allow update: if isVerified() && isPhotoUploaded(); - allow delete: if false; + // The sender can take back a photo message whose photo never arrived: the app's Remove after + // a failed send. Once photoPending is false the photo is delivered and the message stays. A + // text never has photoPending, so it cannot be deleted. + allow delete: if isVerified() + && resource.data.senderUid == request.auth.uid + && resource.data.get('photoPending', false) == true; } } diff --git a/rules-tests/firestore.test.js b/rules-tests/firestore.test.js index 26bd7ee8..6ea4f189 100644 --- a/rules-tests/firestore.test.js +++ b/rules-tests/firestore.test.js @@ -1681,8 +1681,37 @@ describe("pending photos", () => { await assertFails(updateDoc(ref, { photoPending: deleteField() })); }); - test("a pending photo message cannot be deleted", async () => { + test("the sender can delete their message while its photo is pending", async () => { await seedPhotoMessage(); + await assertSucceeds(deleteDoc(doc(verified(BOB), PATH))); + }); + + test("a pending photo with a caption can be deleted", async () => { + await seedPhotoMessage({ photoPending: true, text: "The drill bits" }); + await assertSucceeds(deleteDoc(doc(verified(BOB), PATH))); + }); + + test("only the sender can delete their pending photo message", async () => { + await seedPhotoMessage(); + await assertFails(deleteDoc(doc(verified(ALICE), PATH))); + await assertFails(deleteDoc(doc(verified(EVE), PATH))); + await assertFails(deleteDoc(doc(unverified(BOB), PATH))); + await assertFails(deleteDoc(doc(signedOut(), PATH))); + }); + + test("a photo message cannot be deleted once its photo is uploaded", async () => { + await seedPhotoMessage({ photoPending: false }); + await assertFails(deleteDoc(doc(verified(BOB), PATH))); + }); + + test("a photo sent before photoPending existed cannot be deleted", async () => { + await seedPhotoMessage({}); await assertFails(deleteDoc(doc(verified(BOB), PATH))); }); + + // The app's Remove also deletes a message that was never written; the rules refuse it. + test("a missing message cannot be deleted", async () => { + await seedConversation(); + await assertFails(deleteDoc(doc(verified(BOB), `${CONVERSATION}/messages/m9`))); + }); }); From 71c6e1953bed055576b7ff36d11cb017277631c7 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 19:26:49 +0100 Subject: [PATCH 21/21] fix(chat): delete a failed photo's message when leaving the conversation Co-Authored-By: Claude Opus 5.5 --- .../chat/viewmodel/ConversationViewModel.kt | 28 +++++++++++++------ .../viewmodel/ConversationViewModelTest.kt | 23 +++++++++++++-- 2 files changed, 40 insertions(+), 11 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 7bfb3245..211d8019 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 @@ -354,8 +354,8 @@ class ConversationViewModel( // A refusal from a pause or deletion of the listing also reaches its observation, which // then stops new photos from being attached. _uiState.update { it.withPendingPhoto(pending.failed(exception.toAppError())) } - // Closed: no one can retry it. - if (cleared) deleteIfTaken(pending.photo) + // Closed: no one can retry it, so it is removed as by Remove. + if (cleared) abandon(pending) } } } @@ -385,8 +385,7 @@ class ConversationViewModel( _uiState.update { it.copy(pendingPhotos = it.pendingPhotos.filterNot { p -> p.isSameAs(failed) }) } - chatRepository.deletePhotoMessage(conversationId(listingId, renterUid), messageId) - deleteIfTaken(failed.photo) + abandon(failed) } fun dismissSendError() { @@ -395,19 +394,30 @@ class ConversationViewModel( /** * Deletes the photos taken with the camera that were not sent: the one being taken, the attached - * one and the failed ones. Gallery photos are left alone. The uploads under way keep running in - * [uploadScope] and delete their photo when they end. + * one and the failed ones. Gallery photos are left alone. A failed photo can no longer be + * retried, so it is removed as by [discardPhoto], deleting its message too: it would otherwise + * stay pending for the other participant. The uploads under way keep running in [uploadScope] + * and, when they end, delete their photo, and their message too if they failed. */ override fun onCleared() { cleared = true photoBeingTaken?.let(photoStorage::delete) + val pending = _uiState.value.pendingPhotos + pending.filter { it.status == PendingPhotoStatus.FAILED }.forEach(::abandon) val uploading = - _uiState.value.pendingPhotos - .filter { it.status == PendingPhotoStatus.UPLOADING } - .mapTo(HashSet()) { it.photo } + pending.filter { it.status == PendingPhotoStatus.UPLOADING }.mapTo(HashSet()) { it.photo } takenPhotos.filterNot { it in uploading }.forEach(::deleteIfTaken) } + /** + * Gives up on [photo], which failed: deletes its message, which may be on the server with its + * photo pending, and its file if it was taken with the camera. + */ + private fun abandon(photo: PendingPhoto) { + chatRepository.deletePhotoMessage(conversationId(listingId, renterUid), photo.messageId) + deleteIfTaken(photo.photo) + } + private fun replaceAttachedPhoto(photo: Uri) { val replaced = _uiState.value.attachedPhoto _uiState.update { it.copy(attachedPhoto = photo).derived() } 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 3b2474ca..cb21bac2 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 @@ -1325,6 +1325,7 @@ class ConversationViewModelTest { viewModel.close() assertEquals(listOf(photoStorage.taken.single().uri), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) } @Test @@ -1335,6 +1336,7 @@ class ConversationViewModelTest { viewModel.close() assertEquals(listOf(taken), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) } @Test @@ -1345,6 +1347,7 @@ class ConversationViewModelTest { viewModel.close() assertEquals(emptyList(), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) } @Test @@ -1516,10 +1519,11 @@ class ConversationViewModelTest { advance() assertEquals(1, chat.sentPhotos.size) assertEquals(listOf(attached, sending), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) } @Test - fun closing_whileAPhotoUploads_deletesItsPhotoWhenItFails() { + fun closing_whileAPhotoUploads_deletesItsPhotoAndItsMessageWhenItFails() { val viewModel = inConversation() chat.gate = CompletableDeferred() val sending = viewModel.takePhoto() @@ -1528,11 +1532,14 @@ class ConversationViewModelTest { viewModel.close() assertEquals(emptyList(), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) chat.sendFailure = offline chat.gate!!.complete(Unit) advance() assertEquals(listOf(sending), photoStorage.deleted) + // No one can retry it any more, so it must not stay pending for the other participant. + assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) } @Test @@ -1549,6 +1556,7 @@ class ConversationViewModelTest { assertEquals(1, chat.sentPhotos.size) assertEquals(emptyList(), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) } private val offline = AppException(AppError.NETWORK) @@ -1722,7 +1730,7 @@ class ConversationViewModelTest { } @Test - fun closing_withAFailedTakenPhoto_deletesIt() { + fun closing_withAFailedTakenPhoto_deletesItAndItsMessage() { val viewModel = inConversation() chat.sendFailure = offline val taken = viewModel.takePhoto() @@ -1732,6 +1740,17 @@ class ConversationViewModelTest { viewModel.close() assertEquals(listOf(taken), photoStorage.deleted) + assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) + } + + @Test + fun closing_withAFailedGalleryPhoto_deletesItsMessage_butNotThePhoto() { + val viewModel = failedPhotoSend(refused) + + viewModel.close() + + assertEquals(emptyList(), photoStorage.deleted) + assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) } /**