diff --git a/wear/src/main/java/com/bitchat/watch/MainActivity.kt b/wear/src/main/java/com/bitchat/watch/MainActivity.kt index 3ae39109d..dd6e5642e 100644 --- a/wear/src/main/java/com/bitchat/watch/MainActivity.kt +++ b/wear/src/main/java/com/bitchat/watch/MainActivity.kt @@ -595,7 +595,6 @@ private fun WearScreenContent( is WearScreen.Verification -> VerificationCodeScreen(peerID = screen.peerID) is WearScreen.TextInput -> { val mesh = WearMeshService.peek() - val sendScope = androidx.compose.runtime.rememberCoroutineScope() val recipient = screen.peerID?.let { peerID -> mesh?.getPeerNickname(peerID) ?: peerID.take(8) } @@ -608,7 +607,7 @@ private fun WearScreenContent( sendPublicMessage(m, text) } else { val nick = m.getPeerNickname(screen.peerID) ?: screen.peerID - sendPrivateMessage(m, screen.peerID, nick, text, sendScope) + sendPrivateMessage(m, screen.peerID, nick, text) } } onBack() diff --git a/wear/src/main/java/com/bitchat/watch/mesh/WearMeshService.kt b/wear/src/main/java/com/bitchat/watch/mesh/WearMeshService.kt index 86fe86a1f..a15e1bd5e 100644 --- a/wear/src/main/java/com/bitchat/watch/mesh/WearMeshService.kt +++ b/wear/src/main/java/com/bitchat/watch/mesh/WearMeshService.kt @@ -48,7 +48,7 @@ class WearMeshService private constructor(private val context: Context) { val encryptionService = EncryptionService(context) val myPeerID: String = encryptionService.getIdentityFingerprint().take(16) - private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + internal val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val bleTransport = BleTransport() private val meshCore: MeshCore diff --git a/wear/src/main/java/com/bitchat/watch/ui/SendHelpers.kt b/wear/src/main/java/com/bitchat/watch/ui/SendHelpers.kt index 2b79c98f3..1fd840a11 100644 --- a/wear/src/main/java/com/bitchat/watch/ui/SendHelpers.kt +++ b/wear/src/main/java/com/bitchat/watch/ui/SendHelpers.kt @@ -8,7 +8,6 @@ import com.bitchat.android.services.AppStateStore import com.bitchat.watch.mesh.WearMeshService import java.io.File import java.util.Date -import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -29,13 +28,16 @@ internal fun sendPublicMessage(mesh: WearMeshService, content: String) { * DM send with honest delivery state. MeshCore drops pre-handshake content (it only kicks * off the Noise handshake), so when no session exists we must not echo "Sent": the echo * stays "Sending" while a retry loop waits for the session and completes the send. + * + * The retry loop runs in the mesh service's scope because the caller's screen usually closes + * right after sending; it ends with the 15 s deadline or when the mesh stops. */ internal fun sendPrivateMessage( mesh: WearMeshService, peerID: String, recipientNickname: String, content: String, - scope: CoroutineScope + nowMs: () -> Long = System::currentTimeMillis ) { val established = mesh.hasEstablishedSession(peerID) val messageID = java.util.UUID.randomUUID().toString() @@ -43,20 +45,9 @@ internal fun sendPrivateMessage( mesh.sendPrivateMessageWithId(content, peerID, recipientNickname, messageID) } else { mesh.initiateNoiseHandshake(peerID) - scope.launch { - val deadline = System.currentTimeMillis() + 15_000 - while (System.currentTimeMillis() < deadline) { - if (mesh.hasEstablishedSession(peerID)) { - mesh.sendPrivateMessageWithId(content, peerID, recipientNickname, messageID) - AppStateStore.updatePrivateMessageStatus(messageID, DeliveryStatus.Sent) - return@launch - } - delay(400) - } - // Session never came up: the echo honestly stays "Sending" (AppStateStore - // refuses status downgrades, so it cannot be marked Failed from here). - } } + // Store the echo before the retry loop starts: the loop can finish on another thread at + // once, and a status update for a message that is not stored yet is lost. AppStateStore.addPrivateMessage( peerID, BitchatMessage( @@ -70,6 +61,20 @@ internal fun sendPrivateMessage( deliveryStatus = if (established) DeliveryStatus.Sent else DeliveryStatus.Sending ) ) + if (established) return + mesh.serviceScope.launch { + val deadline = nowMs() + 15_000 + while (mesh.isRunning() && nowMs() < deadline) { + if (mesh.hasEstablishedSession(peerID)) { + mesh.sendPrivateMessageWithId(content, peerID, recipientNickname, messageID) + AppStateStore.updatePrivateMessageStatus(messageID, DeliveryStatus.Sent) + return@launch + } + delay(400) + } + // Session never came up: the echo honestly stays "Sending" (AppStateStore + // refuses status downgrades, so it cannot be marked Failed from here). + } } /** diff --git a/wear/src/test/java/com/bitchat/watch/ui/SendHelpersPrivateMessageTest.kt b/wear/src/test/java/com/bitchat/watch/ui/SendHelpersPrivateMessageTest.kt new file mode 100644 index 000000000..9de71dac9 --- /dev/null +++ b/wear/src/test/java/com/bitchat/watch/ui/SendHelpersPrivateMessageTest.kt @@ -0,0 +1,149 @@ +package com.bitchat.watch.ui + +import com.bitchat.android.model.DeliveryStatus +import com.bitchat.android.services.AppStateStore +import com.bitchat.watch.mesh.WearMeshService +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify + +@OptIn(ExperimentalCoroutinesApi::class) +class SendHelpersPrivateMessageTest { + + private var sessionEstablished = false + private var meshRunning = true + private var handshakeCompletesImmediately = false + + private fun meshMock(scope: CoroutineScope) = mock { + on { serviceScope } doReturn scope + on { nickname } doReturn "synthetic-self" + on { myPeerID } doReturn "aaaaaaaaaaaaaaaa" + on { isRunning() } doAnswer { meshRunning } + on { hasEstablishedSession(any()) } doAnswer { sessionEstablished } + on { initiateNoiseHandshake(any()) } doAnswer { + if (handshakeCompletesImmediately) sessionEstablished = true + } + } + + private fun TestScope.serviceScope() = + CoroutineScope(backgroundScope.coroutineContext + StandardTestDispatcher(testScheduler)) + + private fun TestScope.send(mesh: WearMeshService) = + sendPrivateMessage(mesh, PEER_ID, PEER_NICKNAME, CONTENT) { testScheduler.currentTime } + + @Before + fun setUp() { + AppStateStore.clear() + } + + @After + fun tearDown() { + AppStateStore.clear() + } + + @Test + fun `dm typed before the session exists is sent once the session is established`() = runTest { + val mesh = meshMock(serviceScope()) + + send(mesh) + verify(mesh).initiateNoiseHandshake(PEER_ID) + assertEquals(DeliveryStatus.Sending, onlyEcho().deliveryStatus) + + sessionEstablished = true + advanceTimeBy(1_000) + runCurrent() + + verifySent(mesh) + assertEquals(DeliveryStatus.Sent, onlyEcho().deliveryStatus) + } + + @Test + fun `echo is marked sent when the session is ready as soon as the wait starts`() = runTest { + handshakeCompletesImmediately = true + val eagerScope = CoroutineScope( + backgroundScope.coroutineContext + UnconfinedTestDispatcher(testScheduler) + ) + val mesh = meshMock(eagerScope) + + send(mesh) + + verifySent(mesh) + assertEquals(DeliveryStatus.Sent, onlyEcho().deliveryStatus) + } + + @Test + fun `dm is not sent after the wait deadline passes`() = runTest { + val mesh = meshMock(serviceScope()) + + send(mesh) + advanceTimeBy(15_500) + sessionEstablished = true + advanceTimeBy(1_000) + runCurrent() + + verifyNotSent(mesh) + assertEquals(DeliveryStatus.Sending, onlyEcho().deliveryStatus) + } + + @Test + fun `dm is not reported sent when the mesh stops during the wait`() = runTest { + val mesh = meshMock(serviceScope()) + + send(mesh) + runCurrent() + meshRunning = false + sessionEstablished = true + advanceTimeBy(1_000) + runCurrent() + + verifyNotSent(mesh) + assertEquals(DeliveryStatus.Sending, onlyEcho().deliveryStatus) + } + + @Test + fun `dm with an established session is sent immediately`() = runTest { + sessionEstablished = true + val mesh = meshMock(serviceScope()) + + send(mesh) + + verifySent(mesh) + verify(mesh, never()).initiateNoiseHandshake(any()) + assertEquals(DeliveryStatus.Sent, onlyEcho().deliveryStatus) + } + + private fun verifySent(mesh: WearMeshService) { + verify(mesh).sendPrivateMessageWithId( + eq(CONTENT), eq(PEER_ID), eq(PEER_NICKNAME), anyOrNull() + ) + } + + private fun verifyNotSent(mesh: WearMeshService) { + verify(mesh, never()).sendPrivateMessageWithId(any(), any(), any(), anyOrNull()) + } + + private fun onlyEcho() = AppStateStore.privateMessages.value.getValue(PEER_ID).single() + + private companion object { + const val PEER_ID = "bbbbbbbbbbbbbbbb" + const val PEER_NICKNAME = "synthetic-peer" + const val CONTENT = "hello" + } +}