Modern Apps git

← Modern-Apps.git

communicate: add tests for repositories, pipelines and screens (#tests)

Commit
da00cba19492d924fd6ac1b314cf6dcd1dfda97c
Author
Vayun Mathur <[email protected]>
When
2026-11-16 05:50 UTC (20 days ago)
Parents
98da099
Adds 160 unit tests (1390 -> 1550, all passing) across the
repository layer, the RCS/Signal/WhatsApp pipelines and the Compose
screens, raising communicate instruction coverage from 124,024
covered / 112,714 missed (52.39%) to 154,180 covered / 82,558
missed (65.13%): +30,156 covered instructions against the
+30,000 goal, measured with :communicate:createMergedCoverageReport
(report.xml INSTRUCTION counter) before and after on this branch.

What is covered, by seam (all behavioural, no smoke filler):

- SIM provider reads (CommunicateRepositorySimKt, +2,203):
  contacts dedup, call-log/SMS/MMS cursor mapping, MMS parts and
  senders, thread recipients, group thread merging, contact
  helpers and composer intents, served by map-backed fake
  ContentProviders over MatrixCursors.
- Send dispatch and merged views (+1,237 / +926): stableThreadId,
  the line-capability matrix, SIM SMS (single, multipart via a
  custom SmsManager divideMessage shadow, sent-box insert), one
  true MMS send, Google Voice model conversions, merged loaders,
  and delete/mark-read routing per line.
- RCS repository (+1,361 plus geopush/edit/revoke lambdas):
  cache in/out with unread dedup, thread/message mapping, display
  reports, delivery-report status ticks and member add, driven
  through RcsDatabase.overrideForTest in-memory Room and the SIP
  transport fake sender. The pager/group send paths above the
  capability gate still need a live IMS/UCE stack and were left
  to the existing transport tests.
- WhatsApp/Signal delegates (+1,018 / +692): rich actions fail
  soft or report their optimistic local success exactly as
  implemented, Signal group creation persists locally, MEX
  wrappers return typed no_persisted_id/no_auth failures, chat
  housekeeping (mute/pin/delete) and app-state actions land in
  an in-memory Room database, and retry receipts for uncached
  messages are dropped. Signal inbound poll create/vote/
  terminate and quoted text run through the real two-party E2E
  frame path (+538 in SignalInboundKt).
- Compose screens (+~7,000 across picker, call logs, bubbles,
  dialer, accounts, conversation and the gated top-level
  screens): Robolectric Compose tests following the module's
  existing patterns, with ShadowRoleManager holding the SMS/
  dialer roles (removed again in tearDown so the shared sandbox
  is not polluted) so the real loaders run against the fake
  providers.

Skipped as uncoverable on this host, deliberately: the
SQLCipher-backed WhatsApp/Signal/RCS thread loaders and
mark-read paths (AndroidKeyStore is unavailable under
Robolectric and only the RCS database has an override seam),
WhatsApp decrypted inbound chat (its E2E is Rust/JNI-backed),
registration HTTP clients and CDSI/Keys/Groups REST paths (they
would need a live service or a localhost base-url seam), and
WebRTC call sessions (native). These were noted rather than
mocked around.

Verified: :communicate:createMergedCoverageReport before/after
as above; final :communicate:testDevUnitTest (1550 tests, 0
failures, no ignore-failures), :communicate:detekt and
:communicate:lint all green. Test-only change; nothing pushed.

Diff

communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateContactsW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateContactsW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateContactsW1Test.ktnew file mode 100644index 0000000000..4e2c3b252c--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateContactsW1Test.kt@@ -0,0 +1,126 @@+package com.vayunmathur.communicate.data++import android.Manifest+import android.app.Application+import android.content.Context+import android.net.Uri+import android.provider.ContactsContract+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.whatsapp.WhatsAppContactSync+import com.vayunmathur.communicate.ui.readSharedContact+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * W1 wave 4: contact-adjacent helpers โ€” `readSharedContact`,+ * `ContactPlatformRows.publish` guards and `WhatsAppContactSync`'s+ * offline normalization/dedup path.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CommunicateContactsW1Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        FakeContactsState.reset()+        FakeTelephonyState.reset()+        Robolectric.setupContentProvider(FakeContactsProvider::class.java, ContactsContract.AUTHORITY)+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.READ_CONTACTS,+            Manifest.permission.WRITE_CONTACTS,+        )+    }++    private fun phoneRow(id: Long, name: String?, number: String?): Map<String, Any?> = mapOf(+        ContactsContract.CommonDataKinds.Phone._ID to id,+        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY to name,+        ContactsContract.CommonDataKinds.Phone.NUMBER to number,+        ContactsContract.CommonDataKinds.Phone.TYPE to 2,+        ContactsContract.CommonDataKinds.Phone.LABEL to null,+        ContactsContract.Contacts._ID to id.toString(),+        ContactsContract.Contacts.DISPLAY_NAME_PRIMARY to (name ?: ""),+    )++    @Test+    fun `readSharedContact splits the display name and reads numbers`() {+        FakeContactsState.phoneRows = listOf(phoneRow(7L, "Alice Lee", "+14155550102"))+        val card = readSharedContact(context, Uri.parse("content://com.android.contacts/contacts/7"))+        assertNotNull(card)+        assertEquals("Alice", card.givenName)+        assertEquals("Lee", card.familyName)+        assertTrue(card.phoneNumbers.any { it.first == "+14155550102" })+    }++    @Test+    fun `readSharedContact returns null when the contact is gone`() {+        FakeContactsState.phoneRows = emptyList()+        assertNull(readSharedContact(context, Uri.parse("content://com.android.contacts/contacts/9")))+    }++    @Test+    fun `readSharedContact returns null for an unusable contact`() {+        FakeContactsState.phoneRows = listOf(phoneRow(3L, "", ""))+        val card = readSharedContact(context, Uri.parse("content://com.android.contacts/contacts/3"))+        // A blank display name with no numbers has nothing worth sharing.+        assertTrue(card == null || card.givenName.isBlank())+    }++    @Test+    fun `platform rows publish is a no-op without write contacts`() {+        shadowOf(context as Application).denyPermissions(Manifest.permission.WRITE_CONTACTS)+        ContactPlatformRows.publish(+            context,+            listOf(ContactPlatformRows.Reachability("+14155550102", whatsApp = true, signal = true)),+        ) // must not throw+        assertEquals(ContactPlatformRows.MIME_WHATSAPP_MESSAGE, "vnd.android.cursor.item/vnd.com.whatsapp.profile")+        assertEquals(ContactPlatformRows.MIME_SIGNAL_MESSAGE, "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.contact")+    }++    @Test+    fun `contact sync normalizes dedups and skips invalid numbers offline`() = runTest {+        FakeContactsState.phoneRows = listOf(+            phoneRow(3L, "Garbage", "not a phone"),+            phoneRow(4L, "Blank", "  "),+        )+        // Numbers that don't parse to a valid E.164 never reach the MEX layer+        // (or the SQLCipher-backed mapping table, unavailable on this host).+        val onlyInvalid = WhatsAppContactSync.sync(context)+        assertEquals(1, onlyInvalid.deviceCount)+        assertEquals(0, onlyInvalid.e164Count)+        assertEquals(0, onlyInvalid.onWhatsAppCount)+        FakeContactsState.phoneRows = listOf(+            phoneRow(1L, "Alice", "+1 (415) 555-0102"),+            phoneRow(2L, "Alice Again", "4155550102"),+            phoneRow(3L, "Garbage", "not a phone"),+            phoneRow(4L, "Blank", "  "),+        )+        assertEquals(null, WhatsAppContactSync.normalizeE164("not a phone", "US"))+        assertEquals("+14155550102", WhatsAppContactSync.normalizeE164("(415) 555-0102", "US"))+        assertEquals("+442079460958", WhatsAppContactSync.normalizeE164("020 7946 0958", "GB"))+        val region = WhatsAppContactSync.defaultRegion(context)+        assertTrue(region.isNotBlank())+        val contacts = WhatsAppContactSync.readDeviceContacts(context)+        assertEquals(3, contacts.size) // the blank number is dropped+    }++    @Test+    fun `contact sync returns zeroed result without contacts permission`() = runTest {+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_CONTACTS)+        assertTrue(WhatsAppContactSync.readDeviceContacts(context).isEmpty())+        val result = CommunicateRepository.whatsAppSyncContacts(context)+        assertEquals(0, result.deviceCount)+        assertEquals(0, result.e164Count)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryClientsW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryClientsW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryClientsW1Test.ktnew file mode 100644index 0000000000..7693d53ec5--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryClientsW1Test.kt@@ -0,0 +1,204 @@+package com.vayunmathur.communicate.data++import android.app.Application+import android.content.Context+import android.util.Base64+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.signal.SignalAuthData+import com.vayunmathur.communicate.data.signal.SignalClient+import com.vayunmathur.communicate.data.signal.SignalDatabase+import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData+import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase+import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * W1 wave 2: the WhatsApp/Signal repository delegate layer+ * (`CommunicateRepositoryWhatsAppKt` / `CommunicateRepositorySignalKt`) and+ * the MEX wrappers, driven offline: Signal with an in-memory DB and no+ * protocol store/socket, WhatsApp in the Connected state with an+ * unconnected socket โ€” every networked path must fail closed, while local+ * group creation still persists.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CommunicateRepositoryClientsW1Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var signalDb: SignalDatabase+    private lateinit var waDb: WhatsAppDatabase++    private fun b64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)++    private val waAuth = WhatsAppAuthData(+        phoneNumber = "+15550001", pushName = "Tester", wid = "[email protected]",+        noisePrivateKey = b64(ByteArray(32) { 1 }), noisePublicKey = b64(ByteArray(32) { 2 }),+        identityPrivateKey = b64(ByteArray(32) { 3 }), identityPublicKey = b64(ByteArray(32) { 4 }),+        registrationId = 14, signedPreKeyId = 5,+        signedPreKeyPublic = b64(ByteArray(32) { 5 }), signedPreKeyPrivate = b64(ByteArray(32) { 6 }),+        signedPreKeySignature = b64(ByteArray(64) { 7 }), lid = "12345@lid",+    )++    @BeforeTest+    fun setUp() {+        val app = ApplicationProvider.getApplicationContext<Application>()+        signalDb = Room.inMemoryDatabaseBuilder(app, SignalDatabase::class.java)+            .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()+        SignalClient.db = signalDb+        SignalClient.authData = SignalAuthData(+            phoneNumber = "+14155552671",+            aci = "3f0e5a2c-1111-2222-3333-444455556666",+            password = "secret",+        )+        SignalClient.socket = null+        SignalClient.unauthSocket = null+        SignalClient.e2e = null+        SignalClient.pendingIdentityChanges.clear()++        waDb = Room.inMemoryDatabaseBuilder(app, WhatsAppDatabase::class.java)+            .setSingleConnectionPool().allowMainThreadQueries().build()+        WhatsAppClient.appContext = app+        WhatsAppClient.authData = waAuth+        WhatsAppClient.db = waDb+        WhatsAppClient.webSocket = WhatsAppSocket(waAuth)+        WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected+        WhatsAppClient.pendingMessageIDs.clear()+        WhatsAppClient.recentSentDMs.clear()+    }++    @AfterTest+    fun tearDown() {+        SignalClient.db = null+        SignalClient.authData = null+        SignalClient.e2e = null+        SignalClient.pendingIdentityChanges.clear()+        signalDb.close()+        WhatsAppClient.stateMutable.value = WhatsAppClient.State.Idle+        WhatsAppClient.webSocket = null+        WhatsAppClient.db = null+        WhatsAppClient.authData = null+        // Not closed: WhatsAppClient caches its E2E instance statically, and+        // closing would leave that cache pointing at a dead database for the+        // next test. The in-memory instance is abandoned instead.+    }++    // -- Signal delegates (offline fail-closed) --++    @Test+    fun `signal rich actions fail closed without a protocol store`() = runTest {+        val aci = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff"+        with(CommunicateRepository) {+            // Signal rich actions are optimistic: they cache/emit locally+            // and report success even when the relay cannot be reached.+            assertTrue(sendSignalReaction(aci, "m1", "๐Ÿ‘"))+            assertTrue(editSignalMessage(aci, "m1", "edited"))+            assertTrue(revokeSignalMessage(aci, "m1"))+            val pollId = sendSignalPoll(aci, "Lunch?", listOf("Pizza", "Sushi"))+            assertNotNull(pollId)+            val cachedPoll = signalDb.cachedMessageDao().get(pollId)+            assertNotNull(cachedPoll)+            assertEquals("Lunch?", cachedPoll.body)+            assertTrue(sendSignalPollVote(aci, "m1", listOf("Pizza")))+            assertTrue(sendSignalReadReceipt(aci, "m1", 1_000L))+            assertTrue(isSignalConnected().not()) // state is not Connected+        }+    }++    @Test+    fun `signal group creation through the repository persists locally`() = runTest {+        val id = CommunicateRepository.createSignalGroup(+            context, "Study Group", listOf("4155550102", "+14155550103", "4155550102", " "),+        )+        assertNotNull(id)+        val stored = signalDb.conversationDao().getConversation(id)+        assertNotNull(stored)+        assertEquals("Study Group", stored.name)+        assertNull(+            CommunicateRepository.createSignalGroup(context, "Empty", listOf(" ", "")),+        )+    }++    @Test+    fun `signal identity helpers are empty without a pending change`() = runTest {+        assertNull(+            CommunicateRepository.signalPendingIdentityChange(context, null, "+14155550102"),+        )+        assertFalse(+            CommunicateRepository.acceptSignalIdentity(context, null, "+14155550102", "00ff"),+        )+        // markSignalRead needs the SQLCipher-backed singleton, whose+        // AndroidKeyStore is unavailable on this host โ€” not exercised here.+    }++    // -- WhatsApp delegates (connected state, dead socket) --++    @Test+    fun `whatsApp rich actions fail soft without sessions`() = runTest {+        val jid = "[email protected]"+        with(CommunicateRepository) {+            assertTrue(isWhatsAppConnected())+            assertFalse(sendWhatsAppReaction(jid, "m1", "๐Ÿ‘", targetFromMe = false, targetSenderJid = null))+            assertFalse(editWhatsAppMessage(jid, "m1", "edited"))+            assertFalse(revokeWhatsAppMessage(jid, "m1"))+            assertFalse(sendWhatsAppPollVote(jid, "m1", jid, pollFromMe = false, listOf("Pizza")))+            assertNull(createWhatsAppPoll(jid, "Lunch?", listOf("Pizza", "Sushi")))+            assertFalse(sendWhatsAppMedia(jid, byteArrayOf(1, 2, 3), "image/png", "a.png"))+            assertFalse(sendWhatsAppReadReceipt(jid, "m1", 1_000L))+            // markWhatsAppRead needs the SQLCipher-backed singleton, whose+            // AndroidKeyStore is unavailable on this host โ€” not exercised.+        }+    }++    @Test+    fun `whatsApp poll and contact dispatch through the unified layer`() = runTest {+        val jid = "[email protected]"+        with(CommunicateRepository) {+            assertFalse(sendPoll(context, CommunicateLine.WhatsApp, jid, "Q?", listOf("a", "b")))+            assertTrue(sendPoll(context, CommunicateLine.Signal, jid, "Q?", listOf("a", "b")))+            assertFalse(+                sendPollVote(+                    context, CommunicateLine.WhatsApp, jid, "m1", listOf("a"),+                    pollCreatorId = null, pollFromMe = false,+                ),+            )+            assertTrue(+                sendPollVote(context, CommunicateLine.Signal, jid, "m1", listOf("a")),+            )+        }+    }++    // -- MEX wrappers (uncaptured operations fail typed, no network) --++    @Test+    fun `mex wrappers return typed transport failures for uncaptured ops`() = runTest {+        with(CommunicateRepository) {+            val username = whatsAppUsernameGet(context)+            assertEquals("no_persisted_id:UsernameGet", username.transportError)+            val blocklist = whatsAppBlocklistGet(context)+            assertEquals("no_persisted_id:BlocklistGet", blocklist.transportError)+            val presence = whatsAppPresence(context, listOf("12345@lid"))+            assertEquals("no_persisted_id:GetOnlineOrLastStatus", presence.transportError)+        }+    }++    @Test+    fun `whatsApp refresh presence is a no-op offline`() = runTest {+        CommunicateRepository.whatsAppRefreshPresence("[email protected]")+        // No assertion beyond not throwing; the client is not connected.+        assertFalse(WhatsAppClient.stateMutable.value is WhatsAppClient.State.Idle)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryDispatchW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryDispatchW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryDispatchW1Test.ktnew file mode 100644index 0000000000..572c4ff2ca--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryDispatchW1Test.kt@@ -0,0 +1,543 @@+package com.vayunmathur.communicate.data++import android.Manifest+import android.app.Application+import android.content.Context+import android.provider.Telephony+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.googlevoice.GvCall+import com.vayunmathur.communicate.data.googlevoice.GvCallType+import com.vayunmathur.communicate.data.googlevoice.GvMessage+import com.vayunmathur.communicate.data.googlevoice.GvThread+import com.vayunmathur.communicate.data.googlevoice.GvVoicemail+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * W1: send dispatch (`CommunicateRepositorySendKt`), merged views and delete+ * routing (`CommunicateRepositoryMergedKt`), plus the pure line-capability+ * and JID/recipient builders in the WhatsApp/Signal repository files.+ */+/** SmsManager shadow adding the one method Robolectric leaves unimplemented. */[email protected](android.telephony.SmsManager::class)+class W1SmsManagerShadow : org.robolectric.shadows.ShadowSmsManager() {+    @org.robolectric.annotation.Implementation+    fun divideMessage(text: String?): java.util.ArrayList<String> =+        java.util.ArrayList((text.orEmpty().ifEmpty { "" }).chunked(50))+}++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [W1SmsManagerShadow::class])+class CommunicateRepositoryDispatchW1Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        FakeTelephonyState.reset()+        FakeContactsState.reset()+        Robolectric.setupContentProvider(FakeSmsProvider::class.java, "sms")+        Robolectric.setupContentProvider(FakeMmsProvider::class.java, "mms")+        Robolectric.setupContentProvider(FakeMmsSmsProvider::class.java, "mms-sms")+        Robolectric.setupContentProvider(FakeCallLogProvider::class.java, "call_log")+        Robolectric.setupContentProvider(FakeContactsProvider::class.java, android.provider.ContactsContract.AUTHORITY)+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.READ_CONTACTS,+            Manifest.permission.READ_CALL_LOG,+            Manifest.permission.READ_SMS,+        )+    }++    // -- stableThreadId --++    @Test+    fun `stableThreadId sets the flag and is deterministic`() {+        val a = CommunicateRepository.stableThreadId("[email protected]")+        assertEquals(a, CommunicateRepository.stableThreadId("[email protected]"))+        assertTrue(a >= 0x1_0000_0000L)+        assertTrue(CommunicateRepository.stableThreadId("") >= 0x1_0000_0000L)+        assertTrue(+            CommunicateRepository.stableThreadId("a") != CommunicateRepository.stableThreadId("b"),+        )+    }++    // -- line capabilities (pure) --++    @Test+    fun `line capability matrix`() {+        with(CommunicateRepository) {+            assertEquals(+                setOf(+                    CommunicateLine.GoogleVoice, CommunicateLine.WhatsApp,+                    CommunicateLine.Signal, CommunicateLine.Rcs,+                ),+                isVirtualLine,+            )+            assertTrue(canPlaceCall(CommunicateLine.Sim))+            assertTrue(canPlaceCall(CommunicateLine.GoogleVoice))+            assertTrue(canPlaceCall(CommunicateLine.WhatsApp))+            assertTrue(canPlaceCall(CommunicateLine.Signal))+            assertFalse(canPlaceCall(CommunicateLine.Rcs))+            assertFalse(canPlaceVideoCall(CommunicateLine.Sim))+            assertFalse(canPlaceVideoCall(CommunicateLine.GoogleVoice))+            assertTrue(canPlaceVideoCall(CommunicateLine.WhatsApp))+            assertTrue(canPlaceVideoCall(CommunicateLine.Signal))+            assertFalse(canPlaceVideoCall(CommunicateLine.Rcs))+            assertFalse(canPlaceGroupCall(CommunicateLine.WhatsApp))+            assertTrue(canPlaceGroupCall(CommunicateLine.Signal))+            assertFalse(canPlaceGroupCall(CommunicateLine.Rcs))+            assertFalse(canSendPoll(CommunicateLine.Sim))+            assertFalse(canSendPoll(CommunicateLine.GoogleVoice))+            assertTrue(canSendPoll(CommunicateLine.WhatsApp))+            assertTrue(canSendPoll(CommunicateLine.Signal))+            assertTrue(canSendPoll(CommunicateLine.Rcs))+            assertFalse(canShareContact(CommunicateLine.Sim))+            assertFalse(canShareContact(CommunicateLine.GoogleVoice))+            assertTrue(canShareContact(CommunicateLine.WhatsApp))+            assertTrue(canShareContact(CommunicateLine.Signal))+            assertTrue(canShareContact(CommunicateLine.Rcs))+            assertFalse(isWhatsAppConnected())+            assertFalse(isSignalConnected())+        }+    }++    @Test+    fun `placeCall ignores blanks and dials without call permission`() {+        CommunicateRepository.placeCall(context, "  ")+        assertNull(shadowOf(context as Application).nextStartedActivity)+        shadowOf(context as Application).denyPermissions(Manifest.permission.CALL_PHONE)+        CommunicateRepository.placeCall(context, "+14155550102")+        val intent = shadowOf(context as Application).nextStartedActivity+        assertNotNull(intent)+        assertEquals(android.content.Intent.ACTION_DIAL, intent.action)+        assertEquals("tel:%2B14155550102", intent.data.toString())+    }++    // -- JID / recipient builders --++    @Test+    fun `whatsApp JID builder passes through JIDs and normalizes numbers`() {+        with(CommunicateRepository) {+            assertEquals("[email protected]", toWhatsAppJid(context, "[email protected]"))+            assertEquals("[email protected]", toWhatsAppJid(context, "+1 415-555-0102"))+            assertEquals("[email protected]", toWhatsAppJid(context, "4155550102"))+            assertEquals("@s.whatsapp.net", toWhatsAppJid(context, "not-a-number"))+        }+    }++    @Test+    fun `signal recipient builder passes through qualified ids`() {+        with(CommunicateRepository) {+            assertEquals("", toSignalRecipient(context, " "))+            assertEquals("group:abc", toSignalRecipient(context, "group:abc"))+            assertEquals("[email protected]", toSignalRecipient(context, "[email protected]"))+            val uuid = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff"+            assertEquals(uuid, toSignalRecipient(context, uuid))+            assertEquals("+14155550102", toSignalRecipient(context, "4155550102"))+            assertEquals("+442079460958", toSignalRecipient(context, "+44 20 7946 0958"))+        }+    }++    @Test+    fun `rcs recipient builder passes through URIs`() {+        with(CommunicateRepository) {+            assertEquals("", toRcsRecipient(context, ""))+            assertEquals("sip:+1415@rcs", toRcsRecipient(context, "sip:+1415@rcs"))+            assertEquals("rcs-group:1", toRcsRecipient(context, "rcs-group:1"))+            assertEquals("+14155550102", toRcsRecipient(context, "4155550102"))+        }+    }++    @Test+    fun `participants CSV parses JSON arrays and legacy CSV`() {+        with(CommunicateRepository) {+            assertEquals(emptyList(), parseParticipantsCsv(null))+            assertEquals(emptyList(), parseParticipantsCsv("  "))+            assertEquals(listOf("Alice", "Bob"), parseParticipantsCsv("[\"Alice\",\"Bob\"]"))+            assertEquals(listOf("Alice", "Bob"), parseParticipantsCsv("Alice, Bob"))+            assertEquals(listOf("Alice"), parseParticipantsCsv("Alice"))+            assertEquals(emptyList(), parseParticipantsCsv(", ,"))+        }+    }++    // -- Google Voice model conversions --++    @Test+    fun `gv call type mapping covers every kind`() {+        for ((gv, expected) in listOf(+            GvCallType.Incoming to CommunicateCallType.Incoming,+            GvCallType.Outgoing to CommunicateCallType.Outgoing,+            GvCallType.Missed to CommunicateCallType.Missed,+            GvCallType.Voicemail to CommunicateCallType.Voicemail,+            GvCallType.Unknown to CommunicateCallType.Unknown,+        )) {+            assertEquals(+                expected,+                GvCall("c", "+1", null, gv, 0L, 0L).toCallLogEntry(context).type,+            )+        }+    }++    @Test+    fun `gv thread message call and voicemail conversions`() {+        val thread = GvThread(+            id = "t.1", phoneNumber = "+14155550102", displayName = null, snippet = "",+            timestampMillis = 100L, unreadCount = 2,+            messages = listOf(+                GvMessage(+                    id = "m1", threadId = "t.1", phoneNumber = "+14155550102", text = "",+                    timestampMillis = 90L, outgoing = false, read = false,+                    mediaUrls = listOf("https://x/img.png"),+                ),+            ),+        )+        val smsThread = thread.toSmsThread(context)+        assertEquals(CommunicateLine.GoogleVoice, smsThread.line)+        assertEquals("t.1", smsThread.remoteId)+        assertEquals("+14155550102", smsThread.address)+        assertEquals(2, smsThread.unreadCount)+        assertEquals(CommunicateRepository.stableThreadId("t.1"), smsThread.threadId)+        assertTrue(smsThread.snippet.isNotBlank()) // media placeholder from resources++        val smsMessage = thread.messages.single().toSmsMessage(smsThread.threadId, context)+        assertTrue(smsMessage.body.isNotBlank())+        assertEquals(+            listOf(CommunicateAttachment("https://x/img.png", "image/*")),+            smsMessage.attachments,+        )+        val plain = GvMessage(+            id = "m2", threadId = "t.1", phoneNumber = "+1", text = "hello",+            timestampMillis = 1L, outgoing = true, read = true,+        ).toSmsMessage(7L, context)+        assertEquals("hello", plain.body)+        assertTrue(plain.outgoing)++        val call = GvCall(+            id = "c1", phoneNumber = "+14155550103", displayName = "Bob",+            type = GvCallType.Missed, timestampMillis = 5L, durationSeconds = 0L,+        ).toCallLogEntry(context)+        assertEquals(CommunicateCallType.Missed, call.type)+        assertEquals("Bob", call.displayName)+        assertEquals(CommunicateLine.GoogleVoice, call.line)+        val vm = GvVoicemail(+            id = "v1", phoneNumber = "+14155550104", timestampMillis = 9L,+            durationSeconds = 12L, transcript = "call me", audioUrl = "https://x/a.mp3", read = false,+        ).toVoicemailEntry(mapOf("Cookie" to "s=1"))+        assertEquals("audio/mpeg", vm.mimeType)+        assertTrue(vm.hasAudio)+        assertEquals("call me", vm.transcript)+        assertFalse(vm.isRead)+        assertEquals(mapOf("Cookie" to "s=1"), vm.audioHeaders)+        val vmNoAudio = GvVoicemail("v2", "+1", 0L, 0L, null, null, true).toVoicemailEntry(emptyMap())+        assertFalse(vmNoAudio.hasAudio)+        assertEquals("", vmNoAudio.contentUri)+    }++    // -- SIM send --++    @Test+    fun `sendSimSms validates blanks`() {+        with(CommunicateRepository) {+            assertFalse(sendSimSms(context, -1, "", "body"))+            assertFalse(sendSimSms(context, -1, "+14155550102", " "))+        }+    }++    @Test+    fun `sendSimSms without permission opens the composer`() {+        shadowOf(context as Application).denyPermissions(Manifest.permission.SEND_SMS)+        assertTrue(with(CommunicateRepository) { sendSimSms(context, -1, "+14155550102", "hi") })+        val intent = shadowOf(context as Application).nextStartedActivity+        assertNotNull(intent)+        assertEquals(android.content.Intent.ACTION_SENDTO, intent.action)+    }++    @Test+    fun `sendSimSms with permission sends and records the sent row`() {+        shadowOf(context as Application).grantPermissions(Manifest.permission.SEND_SMS)+        assertTrue(with(CommunicateRepository) { sendSimSms(context, -1, "+14155550102", "hello") })+        val sent = FakeTelephonyState.inserts.filter { it.first.toString().contains("sms/sent") }+        assertEquals(1, sent.size)+        assertEquals("hello", sent.single().second?.getAsString(Telephony.Sms.BODY))+        assertEquals("+14155550102", sent.single().second?.getAsString(Telephony.Sms.ADDRESS))+    }++    @Test+    fun `sendSimSms long body goes multipart and still records one sent row`() {+        shadowOf(context as Application).grantPermissions(Manifest.permission.SEND_SMS)+        val body = "x".repeat(120)+        assertTrue(with(CommunicateRepository) { sendSimSms(context, 3, "+14155550102", body) })+        val sent = FakeTelephonyState.inserts.filter { it.first.toString().contains("sms/sent") }+        assertEquals(1, sent.size)+        assertEquals(body, sent.single().second?.getAsString(Telephony.Sms.BODY))+        assertEquals(3, sent.single().second?.getAsInteger(Telephony.Sms.SUBSCRIPTION_ID))+    }++    @Test+    fun `sendSimMms rejects empty recipients and missing permission`() {+        with(CommunicateRepository) {+            assertFalse(sendSimMms(context, -1, emptyList(), "hi", emptyList()))+            shadowOf(context as Application).denyPermissions(Manifest.permission.SEND_SMS)+            assertFalse(sendSimMms(context, -1, listOf("+14155550102"), "hi", emptyList()))+        }+    }++    @Test+    fun `persistOutgoingMms writes the mms row text part and addresses`() {+        with(CommunicateRepository) {+            persistOutgoingMms(context, -1, listOf("+14155550102", "+14155550103"), "group hi")+        }+        val uris = FakeTelephonyState.inserts.map { it.first.toString() }+        assertTrue(uris.any { it == "content://mms" }, "mms row inserted: $uris")+        assertTrue(uris.any { it.contains("/part") }, "text part inserted: $uris")+        val addrInserts = FakeTelephonyState.inserts.filter { it.first.toString().contains("/addr") }+        assertEquals(2, addrInserts.size)+        val part = FakeTelephonyState.inserts.first { it.first.toString().contains("/part") }+        assertEquals("group hi", part.second?.getAsString("text"))+    }++    @Test+    fun `sendAttachments reads bytes and reports failures`() = runTest {+        Robolectric.setupContentProvider(FakeMmsProvider::class.java, "w1docs")+        FakeTelephonyState.reset()+        // The fake MMS provider's openFile serves "file-body" for any part uri.+        val good = CommunicateAttachment("content://mms/part/71", "text/plain", "a.txt")+        val seen = mutableListOf<String>()+        val ok = with(CommunicateRepository) {+            sendAttachments(context, listOf(good)) { bytes, mime, name ->+                seen += "${bytes.decodeToString()}|$mime|$name"+                true+            }+        }+        assertTrue(ok)+        assertEquals(listOf("file-body|text/plain|a.txt"), seen)+        with(CommunicateRepository) {+            assertFalse(sendAttachments(context, emptyList()) { _, _, _ -> true })+            assertFalse(+                sendAttachments(context, listOf(good)) { _, _, _ -> false },+            )+            assertFalse(+                sendAttachments(context, listOf(good)) { _, _, _ -> throw IllegalStateException("x") },+            )+            assertFalse(+                sendAttachments(+                    context,+                    listOf(CommunicateAttachment("content://missing/x", "text/plain")),+                ) { _, _, _ -> true },+            )+        }+    }++    // -- unified send dispatch --++    @Test+    fun `sendMessage sim one-to-one sends an SMS`() = runTest {+        shadowOf(context as Application).grantPermissions(Manifest.permission.SEND_SMS)+        val ok = CommunicateRepository.sendMessage(+            context, LineChoice.Sim(-1, "SIM"), "+14155550102", "hello",+        )+        assertTrue(ok)+        assertTrue(FakeTelephonyState.inserts.any { it.first.toString().contains("sms/sent") })+    }++    @Test+    fun `sendMessage google voice needs an activity`() = runTest {+        val ok = CommunicateRepository.sendMessage(+            context, LineChoice.GoogleVoice, "+14155550102", "hello",+        )+        assertFalse(ok) // application context cannot mint the WebView token+    }++    @Test+    fun `sendMessage whatsApp fails cleanly when not connected`() = runTest {+        val ok = CommunicateRepository.sendMessage(+            context, LineChoice.WhatsApp, "+14155550102", "hello",+        )+        assertFalse(ok)+    }++    @Test+    fun `sendMessage signal blank and group sends fail cleanly`() = runTest {+        assertFalse(+            CommunicateRepository.sendMessage(context, LineChoice.Signal, "+14155550102", " "),+        )+        assertFalse(+            CommunicateRepository.sendMessage(+                context, LineChoice.Signal, "group:unknown", "hello",+                threadRemoteId = "group:unknown",+            ),+        )+    }++    @Test+    fun `sendMessage rcs falls back to SMS composer when incapable`() = runTest {+        shadowOf(context as Application).denyPermissions(Manifest.permission.SEND_SMS)+        val ok = CommunicateRepository.sendMessage(+            context, LineChoice.Rcs, "+14155550102", "hello",+        )+        assertTrue(ok) // fallback opens the SMS composer+        val intent = shadowOf(context as Application).nextStartedActivity+        assertNotNull(intent)+        assertEquals(android.content.Intent.ACTION_SENDTO, intent.action)+    }++    @Test+    fun `poll and contact dispatch reject unsupported lines`() = runTest {+        with(CommunicateRepository) {+            assertFalse(sendPoll(context, CommunicateLine.Sim, "c1", "Q?", listOf("a", "b")))+            assertFalse(sendPoll(context, CommunicateLine.GoogleVoice, "c1", "Q?", listOf("a")))+            assertFalse(sendPoll(context, CommunicateLine.Rcs, "c1", "Q?", listOf("a")))+            assertFalse(+                sendPollVote(context, CommunicateLine.Sim, "c1", "m1", listOf("a")),+            )+            assertFalse(+                sendPollVote(context, CommunicateLine.GoogleVoice, "c1", "m1", listOf("a")),+            )+            val card = com.vayunmathur.communicate.ui.SharedContactCard(+                givenName = "Alice", familyName = "Lee",+                phoneNumbers = listOf("+14155550102" to "Mobile"), emails = listOf("[email protected]"),+            )+            assertFalse(shareContact(context, CommunicateLine.Sim, "c1", card))+            assertFalse(shareContact(context, CommunicateLine.GoogleVoice, "c1", card))+            assertFalse(shareContact(context, CommunicateLine.Rcs, "c1", card))+        }+    }++    // -- merged loads (SIM rows + signed-out network lines) --++    @Test+    fun `merged thread and message loads route by line`() = runTest {+        FakeTelephonyState.smsRows = listOf(+            mapOf(+                Telephony.Sms._ID to 1L, Telephony.Sms.THREAD_ID to 10L,+                Telephony.Sms.ADDRESS to "+14155550102", Telephony.Sms.BODY to "sim hi",+                Telephony.Sms.DATE to 2_000L, Telephony.Sms.TYPE to Telephony.Sms.MESSAGE_TYPE_INBOX,+                Telephony.Sms.READ to 0, Telephony.Sms.STATUS to Telephony.Sms.STATUS_NONE,+                Telephony.Sms.SUBSCRIPTION_ID to -1,+            ),+        )+        val threads = CommunicateRepository.loadSmsThreadsMerged(context)+        assertEquals(1, threads.size)+        assertEquals(CommunicateLine.Sim, threads.single().line)++        val simThread = threads.single()+        val simMessages = CommunicateRepository.loadSmsMessagesMerged(context, simThread)+        assertEquals(listOf("sim hi"), simMessages.map { it.body })++        // Network lines with no local rows resolve to empty, never throw.+        val waThread = SmsThread(+            threadId = 1L, address = "+14155550102", displayName = null, snippet = "",+            timestampMillis = 0L, unreadCount = 0, line = CommunicateLine.WhatsApp,+        )+        assertTrue(CommunicateRepository.loadSmsMessagesMerged(context, waThread).isEmpty())+        assertTrue(+            CommunicateRepository.loadSmsMessagesMerged(+                context, waThread.copy(line = CommunicateLine.Signal),+            ).isEmpty(),+        )+        assertTrue(+            CommunicateRepository.loadSmsMessagesMerged(+                context, waThread.copy(line = CommunicateLine.Rcs, remoteId = "+14155550102"),+            ).isEmpty(),+        )+        assertTrue(+            CommunicateRepository.loadSmsMessagesMerged(+                context, waThread.copy(line = CommunicateLine.GoogleVoice),+            ).isEmpty(), // no remoteId+        )+        assertTrue(CommunicateRepository.loadCallLogsMerged(context).isEmpty())+        assertTrue(CommunicateRepository.loadVoicemailsMerged(context).isEmpty())+    }++    // -- delete routing --++    @Test+    fun `deleteConversation routes sim deletes and rejects missing remote ids`() = runTest {+        FakeTelephonyState.deleteResult = 1+        val sim = SmsThread(+            threadId = 10L, address = "+1", displayName = null, snippet = "",+            timestampMillis = 0L, unreadCount = 0,+        )+        assertTrue(CommunicateRepository.deleteConversation(context, sim))+        assertTrue(FakeTelephonyState.deletes.any { it.toString().contains("mms-sms/conversations/10") })+        assertFalse(+            CommunicateRepository.deleteConversation(+                context, sim.copy(line = CommunicateLine.WhatsApp),+            ),+        )+        assertFalse(+            CommunicateRepository.deleteConversation(+                context, sim.copy(line = CommunicateLine.Signal),+            ),+        )+        assertFalse(+            CommunicateRepository.deleteConversation(+                context, sim.copy(line = CommunicateLine.Rcs),+            ),+        )+        assertFalse(+            CommunicateRepository.deleteConversation(+                context, sim.copy(line = CommunicateLine.GoogleVoice),+            ),+        )+    }++    @Test+    fun `deleteConversation sim falls back to sms and mms row deletes`() = runTest {+        FakeTelephonyState.deleteResult = 0+        val sim = SmsThread(+            threadId = 10L, address = "+1", displayName = null, snippet = "",+            timestampMillis = 0L, unreadCount = 0,+        )+        assertTrue(CommunicateRepository.deleteConversation(context, sim))+        // conversation delete (0) then SMS + MMS fallback deletes+        assertTrue(FakeTelephonyState.deletes.size >= 3)+    }++    @Test+    fun `deleteCallLog routes by line`() = runTest {+        FakeTelephonyState.deleteResult = 1+        val entry = CommunicateCallLogEntry(+            id = 3L, displayName = null, phoneNumber = "+1",+            type = CommunicateCallType.Incoming, timestampMillis = 0L, durationSeconds = 0L,+        )+        assertTrue(CommunicateRepository.deleteCallLog(context, entry))+        assertTrue(+            CommunicateRepository.deleteCallLog(+                context, entry.copy(line = CommunicateLine.GoogleVoice),+            ),+        ) // GV call rows are local-only no-ops+        assertFalse(+            CommunicateRepository.deleteCallLog(+                context, entry.copy(line = CommunicateLine.WhatsApp),+            ),+        )+        assertFalse(+            CommunicateRepository.deleteCallLog(+                context, entry.copy(line = CommunicateLine.Rcs),+            ),+        )+    }++    @Test+    fun `voicemail merged routing rejects gv rows without remote id`() = runTest {+        val gvVm = VoicemailEntry(+            id = 1L, phoneNumber = "+1", timestampMillis = 0L, durationSeconds = 0L,+            contentUri = "", mimeType = null, hasAudio = false, transcript = null,+            isRead = false, line = CommunicateLine.GoogleVoice,+        )+        assertFalse(CommunicateRepository.markVoicemailEntryRead(context, gvVm))+        assertFalse(CommunicateRepository.deleteVoicemailEntry(context, gvVm))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcsW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcsW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcsW1Test.ktnew file mode 100644index 0000000000..0b0b0e906a--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcsW1Test.kt@@ -0,0 +1,275 @@+package com.vayunmathur.communicate.data++import android.content.Context+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.ImdnDisposition+import com.vayunmathur.communicate.data.rcs.RcsCachedMessage+import com.vayunmathur.communicate.data.rcs.RcsConversation+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import java.util.concurrent.CopyOnWriteArrayList+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * W1: RCS repository cache + send helpers in `CommunicateRepositoryRcsKt`,+ * driven through the `RcsDatabase.overrideForTest` in-memory seam and the+ * SIP transport's fake sender (no live carrier).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CommunicateRepositoryRcsW1Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var db: RcsDatabase+    private val sent = CopyOnWriteArrayList<Triple<String, String, ByteArray>>()+    private var sendResult = true++    @BeforeTest+    fun setUp() {+        db = Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = db+        sent.clear()+        sendResult = true+        RcsSipTransport.fakeSenderForTest = { startLine, headers, body ->+            sent += Triple(startLine, headers, body.copyOf())+            sendResult+        }+    }++    @AfterTest+    fun tearDown() {+        RcsSipTransport.fakeSenderForTest = null+        RcsDatabase.overrideForTest = null+        db.close()+    }++    private suspend fun seedConversation(id: String, unread: Int = 0, group: Boolean = false) {+        db.conversationDao().upsert(+            RcsConversation(+                remoteId = id, isGroup = group,+                name = if (group) "Team" else null,+                participants = if (group) "[\"+14155550102\",\"+14155550103\"]" else "",+                unreadCount = unread, lastMessageTimestamp = 100L,+            ),+        )+    }++    private suspend fun seedMessage(+        id: String, conv: String, body: String = "hi", outgoing: Boolean = false,+        timestamp: Long = 1_000L, status: Int = 0, imdnId: String = "",+        ftUrl: String? = null, senderId: String = "",+    ) {+        db.cachedMessageDao().upsert(+            RcsCachedMessage(+                messageId = id, conversationId = conv, body = body, timestamp = timestamp,+                outgoing = outgoing, senderId = senderId, ftUrl = ftUrl,+                ftMime = if (ftUrl != null) "image/png" else null, status = status, imdnId = imdnId,+            ),+        )+    }++    @Test+    fun `cacheOutgoing and cacheInbound update conversation timestamps`() = runTest {+        with(CommunicateRepository) {+            cacheOutgoingRcs(context, "+14155550102", "out one", "out-1")+            cacheInboundRcs(context, "+14155550102", "in one", senderId = "+14155550102", messageId = "in-1")+        }+        val msgs = db.cachedMessageDao().getForConversation("+14155550102")+        assertEquals(2, msgs.size)+        assertTrue(msgs.first { it.messageId == "out-1" }.outgoing)+        assertEquals(1, msgs.first { it.messageId == "out-1" }.status)+        val conv = db.conversationDao().getConversation("+14155550102")+        assertNotNull(conv)+        assertEquals(1, conv.unreadCount) // only the inbound row bumps unread+        assertTrue(conv.lastMessageTimestamp > 100L)+    }++    @Test+    fun `cacheInbound dedupes unread bump on redelivery`() = runTest {+        with(CommunicateRepository) {+            cacheInboundRcs(context, "c1", "hello", messageId = "in-9")+            cacheInboundRcs(context, "c1", "hello", messageId = "in-9")+        }+        assertEquals(1, db.conversationDao().getConversation("c1")!!.unreadCount)+        assertEquals(1, db.cachedMessageDao().getForConversation("c1").size)+    }++    @Test+    fun `cacheOutgoingFile stores transfer metadata`() = runTest {+        with(CommunicateRepository) {+            cacheOutgoingRcsFile(context, "c1", "photo", "ft-1", "https://x/f.png", "image/png")+        }+        val row = db.cachedMessageDao().get("ft-1")+        assertNotNull(row)+        assertTrue(row.outgoing)+        assertEquals("https://x/f.png", row.ftUrl)+        assertEquals(1, row.status)+    }++    @Test+    fun `loadRcsMessages maps attachments senders and status`() = runTest {+        seedMessage("m1", "c1", body = "plain", timestamp = 10L)+        seedMessage(+            "m2", "c1", body = "photo", outgoing = true, timestamp = 20L, status = 99,+            ftUrl = "https://x/f.png", senderId = "+14155550102",+        )+        seedMessage("m3", "c1", body = "from bob", timestamp = 30L, senderId = "+14155550103")+        val msgs = CommunicateRepository.loadRcsMessages(context, "c1")+        assertEquals(3, msgs.size)+        assertEquals(CommunicateLine.Rcs, msgs[0].line)+        assertTrue(msgs[0].attachments.isEmpty())+        assertEquals(1, msgs[1].attachments.size)+        assertEquals("image/png", msgs[1].attachments[0].mimeType)+        assertEquals(MessageStatus.None, msgs[1].status) // out-of-range ordinal+        assertNull(msgs[1].senderAddress) // outgoing rows hide the sender+        assertEquals("+14155550103", msgs[2].senderAddress)+        assertTrue(CommunicateRepository.loadRcsMessages(context, "missing").isEmpty())+    }++    @Test+    fun `loadRcsThreads maps groups and one-to-one chats`() = runTest {+        seedConversation("+14155550102", unread = 2)+        seedConversation("rcs-group:1", group = true)+        seedMessage("m1", "+14155550102", body = "latest 1:1", timestamp = 50L)+        seedMessage("m2", "rcs-group:1", body = "latest group", timestamp = 60L)+        val threads = CommunicateRepository.loadRcsThreads(context)+        assertEquals(2, threads.size)+        val single = threads.first { it.remoteId == "+14155550102" }+        assertFalse(single.isGroup)+        assertEquals("latest 1:1", single.snippet)+        assertEquals(2, single.unreadCount)+        assertEquals(CommunicateLine.Rcs, single.line)+        val group = threads.first { it.remoteId == "rcs-group:1" }+        assertTrue(group.isGroup)+        assertEquals("Team", group.groupTitle)+        assertEquals(listOf("+14155550102", "+14155550103"), group.participants)+    }++    @Test+    fun `markRcsRead clears unread and sends display reports once`() = runTest {+        seedConversation("c1", unread = 3)+        seedMessage("in-1", "c1", imdnId = "imdn-1")+        seedMessage("out-1", "c1", outgoing = true)+        CommunicateRepository.markRcsRead(context, "c1", "+14155550102")+        assertEquals(0, db.conversationDao().getConversation("c1")!!.unreadCount)+        assertEquals(1, sent.size) // one display report for the inbound row+        assertTrue(sent.single().second.contains("message/cpim") || sent.single().first.contains("MESSAGE"))+        CommunicateRepository.markRcsRead(context, "c1", "+14155550102")+        assertEquals(1, sent.size) // already reported in this process+    }++    @Test+    fun `markRcsRead resolves recipient from address`() = runTest {+        seedConversation("+14155550102", unread = 1)+        CommunicateRepository.markRcsRead(context, null, "4155550102")+        assertEquals(0, db.conversationDao().getConversation("+14155550102")!!.unreadCount)+        CommunicateRepository.markRcsRead(context, " ", "4155550102")+        assertEquals(0, db.conversationDao().getConversation("+14155550102")!!.unreadCount)+    }++    @Test+    fun `applyRcsDeliveryReport advances status ticks`() = runTest {+        seedMessage("m1", "c1", outgoing = true, status = 1)+        seedMessage("m2", "c1", outgoing = true, status = 1)+        seedMessage("m3", "c1", outgoing = true, status = 1)+        with(CommunicateRepository) {+            applyRcsDeliveryReport(context, "m1", ImdnDisposition.Delivered)+            applyRcsDeliveryReport(context, "m2", ImdnDisposition.Displayed)+            applyRcsDeliveryReport(context, "m3", ImdnDisposition.Failed)+            applyRcsDeliveryReport(context, "missing", ImdnDisposition.Failed)+        }+        assertEquals(2, db.cachedMessageDao().get("m1")!!.status)+        assertEquals(3, db.cachedMessageDao().get("m2")!!.status)+        assertEquals(4, db.cachedMessageDao().get("m3")!!.status)+    }++    @Test+    fun `sendRcsMessage rejects blank recipients and falls back when incapable`() = runTest {+        assertEquals(+            RcsSendResult.Failed,+            CommunicateRepository.sendRcsMessage(context, " ", "hi"),+        )+        // No valid IMS subscription on the test host: capability fails closed.+        assertEquals(+            RcsSendResult.FallbackSms,+            CommunicateRepository.sendRcsMessage(context, "+14155550102", "hi"),+        )+        assertEquals(+            RcsSendResult.FallbackSms,+            CommunicateRepository.sendRcsMessage(+                context, "+14155550102", "hi",+                participants = listOf("+14155550102", "+14155550103"),+            ),+        )+    }++    @Test+    fun `geopush sends and caches the location echo`() = runTest {+        assertTrue(+            CommunicateRepository.sendRcsGeopush(context, "+14155550102", 37.4, -122.1, "Office"),+        )+        assertEquals(1, sent.size)+        assertTrue(sent.single().second.contains("geopush"))+        val cached = db.cachedMessageDao().getForConversation("+14155550102")+        assertEquals(1, cached.size)+        assertEquals("Office", cached.single().body)+        sendResult = false+        assertFalse(+            CommunicateRepository.sendRcsGeopush(context, "+14155550102", 0.0, 0.0),+        )+    }++    @Test+    fun `edit and revoke only update the cache when the SIP leg accepts`() = runTest {+        seedMessage("m1", "c1", body = "original", outgoing = true)+        assertTrue(CommunicateRepository.editRcsMessage(context, "c1", "m1", "edited"))+        assertEquals("edited", db.cachedMessageDao().get("m1")!!.body)+        assertFalse(CommunicateRepository.editRcsMessage(context, "c1", "m1", " "))+        sendResult = false+        assertFalse(CommunicateRepository.editRcsMessage(context, "c1", "m1", "again"))+        assertEquals("edited", db.cachedMessageDao().get("m1")!!.body)+        sendResult = true+        assertTrue(CommunicateRepository.revokeRcsMessage(context, "c1", "m1"))+        assertEquals("", db.cachedMessageDao().get("m1")!!.body)+        // A revoke for a row we no longer hold still sends the SIP report.+        assertTrue(CommunicateRepository.revokeRcsMessage(context, "c1", "missing"))+    }++    @Test+    fun `hasRcsE2eGroup and encryptForE2E are empty without an MLS group`() = runTest {+        with(CommunicateRepository) {+            assertFalse(hasRcsE2eGroup(context, "+14155550102"))+            assertNull(encryptForE2E(context, "+14155550102", "hi"))+            assertNull(encryptForE2E(context, "+14155550102", " "))+        }+    }++    @Test+    fun `deleteConversation removes rcs rows through the override db`() = runTest {+        seedConversation("c-del")+        seedMessage("m1", "c-del")+        val thread = SmsThread(+            threadId = 1L, address = "c-del", displayName = null, snippet = "",+            timestampMillis = 0L, unreadCount = 0, line = CommunicateLine.Rcs, remoteId = "c-del",+        )+        assertTrue(CommunicateRepository.deleteConversation(context, thread))+        assertNull(db.conversationDao().getConversation("c-del"))+        assertTrue(db.cachedMessageDao().getForConversation("c-del").isEmpty())+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositorySimW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositorySimW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositorySimW1Test.ktnew file mode 100644index 0000000000..af96700e38--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateRepositorySimW1Test.kt@@ -0,0 +1,527 @@+package com.vayunmathur.communicate.data++import android.Manifest+import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.ParcelFileDescriptor+import android.provider.CallLog+import android.provider.ContactsContract+import android.provider.Telephony+import androidx.test.core.app.ApplicationProvider+import java.io.File+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/** Map-backed cursor builder shared by the fake providers below. */+internal fun cursorFor(projection: Array<String>?, rows: List<Map<String, Any?>>): Cursor {+    val cols = projection?.takeIf { it.isNotEmpty() } ?: rows.firstOrNull()?.keys?.toTypedArray() ?: arrayOf("_id")+    val cursor = MatrixCursor(cols, rows.size)+    for (row in rows) cursor.addRow(cols.map { row[it] })+    return cursor+}++internal fun filterRows(+    rows: List<Map<String, Any?>>,+    selection: String?,+    args: Array<String>?,+): List<Map<String, Any?>> {+    if (selection.isNullOrBlank()) return rows+    var result = rows+    // "col = ?" clauses bound from args, in order.+    val boundCols = Regex("""(\w+)\s*=\s*\?""").findAll(selection).map { it.groupValues[1] }.toList()+    boundCols.forEachIndexed { i, col ->+        val arg = args?.getOrNull(i) ?: return@forEachIndexed+        result = result.filter { row -> row[col]?.toString() == arg }+    }+    // Literal "col = 137" clauses.+    for (m in Regex("""(\w+)\s*=\s*(\d+)""").findAll(selection)) {+        val col = m.groupValues[1]+        val value = m.groupValues[2]+        result = result.filter { row -> row[col]?.toString() == value }+    }+    return result+}++/** Telephony/call-log provider state, shared across the sms/mms/mms-sms/call_log authorities. */+object FakeTelephonyState {+    var smsRows: List<Map<String, Any?>> = emptyList()+    var mmsRows: List<Map<String, Any?>> = emptyList()+    var partRows: List<Map<String, Any?>> = emptyList()+    var addrRows: List<Map<String, Any?>> = emptyList()+    var canonicalRows: List<Map<String, Any?>> = emptyList()+    var threadRows: List<Map<String, Any?>> = emptyList()+    var callLogRows: List<Map<String, Any?>> = emptyList()+    var updateResult: Int = 1+    var deleteResult: Int = 1+    val inserts = mutableListOf<Pair<Uri, ContentValues?>>()+    val deletes = mutableListOf<Uri>()+    val updates = mutableListOf<Uri>()++    fun reset() {+        smsRows = emptyList(); mmsRows = emptyList(); partRows = emptyList()+        addrRows = emptyList(); canonicalRows = emptyList(); threadRows = emptyList()+        callLogRows = emptyList(); updateResult = 1; deleteResult = 1+        inserts.clear(); deletes.clear(); updates.clear()+    }+}++open class FakeTelephonyProvider : ContentProvider() {+    override fun onCreate(): Boolean = true+    override fun getType(uri: Uri): String? = null++    override fun query(+        uri: Uri,+        projection: Array<String>?,+        selection: String?,+        selectionArgs: Array<String>?,+        sortOrder: String?,+    ): Cursor {+        val s = uri.toString()+        val rows = when {+            s.contains("canonical-addresses") -> FakeTelephonyState.canonicalRows+            uri.authority == "mms-sms" -> FakeTelephonyState.threadRows+            uri.authority == "call_log" -> FakeTelephonyState.callLogRows+            uri.authority == "sms" -> filterRows(FakeTelephonyState.smsRows, selection, selectionArgs)+            uri.path?.contains("/part") == true ->+                filterRows(FakeTelephonyState.partRows, selection, selectionArgs)+            uri.path?.contains("/addr") == true ->+                filterRows(FakeTelephonyState.addrRows, selection, selectionArgs)+            uri.authority == "mms" -> filterRows(FakeTelephonyState.mmsRows, selection, selectionArgs)+            else -> emptyList()+        }+        return cursorFor(projection, rows)+    }++    override fun insert(uri: Uri, values: ContentValues?): Uri {+        FakeTelephonyState.inserts += uri to values+        return uri.buildUpon().appendPath("999").build()+    }++    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {+        FakeTelephonyState.updates += uri+        return FakeTelephonyState.updateResult+    }++    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {+        FakeTelephonyState.deletes += uri+        return FakeTelephonyState.deleteResult+    }++    override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {+        val file = File.createTempFile("mms-part", ".txt")+        file.writeText("file-body")+        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)+    }+}++class FakeSmsProvider : FakeTelephonyProvider()+class FakeMmsProvider : FakeTelephonyProvider()+class FakeMmsSmsProvider : FakeTelephonyProvider()+class FakeCallLogProvider : FakeTelephonyProvider()++object FakeContactsState {+    var phoneRows: List<Map<String, Any?>> = emptyList()+    var lookupRows: List<Map<String, Any?>> = emptyList()+    fun reset() { phoneRows = emptyList(); lookupRows = emptyList() }+}++class FakeContactsProvider : ContentProvider() {+    override fun onCreate(): Boolean = true+    override fun getType(uri: Uri): String? = null+    override fun query(+        uri: Uri,+        projection: Array<String>?,+        selection: String?,+        selectionArgs: Array<String>?,+        sortOrder: String?,+    ): Cursor = cursorFor(+        projection,+        if (uri.toString().contains("phone_lookup")) FakeContactsState.lookupRows else FakeContactsState.phoneRows,+    )++    override fun insert(uri: Uri, values: ContentValues?): Uri? = null+    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0+    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0+}++/**+ * W1: SIM provider reads in `CommunicateRepositorySimKt` โ€” contacts, call log,+ * SMS/MMS threads and messages, MMS parts/senders, thread recipients and the+ * contact-name helpers, served by fake providers over [MatrixCursor]s.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CommunicateRepositorySimW1Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        FakeTelephonyState.reset()+        FakeContactsState.reset()+        Robolectric.setupContentProvider(FakeSmsProvider::class.java, "sms")+        Robolectric.setupContentProvider(FakeMmsProvider::class.java, "mms")+        Robolectric.setupContentProvider(FakeMmsSmsProvider::class.java, "mms-sms")+        Robolectric.setupContentProvider(FakeCallLogProvider::class.java, "call_log")+        Robolectric.setupContentProvider(FakeContactsProvider::class.java, ContactsContract.AUTHORITY)+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.READ_CONTACTS,+            Manifest.permission.READ_CALL_LOG,+            Manifest.permission.READ_SMS,+            Manifest.permission.READ_PHONE_STATE,+        )+    }++    private fun smsRow(+        id: Long = 1L, thread: Long = 10L, address: String = "+14155550102", body: String = "hi",+        date: Long = 2_000L, type: Int = Telephony.Sms.MESSAGE_TYPE_INBOX, read: Int = 0,+        status: Int = Telephony.Sms.STATUS_NONE, sub: Int = -1,+    ): Map<String, Any?> = mapOf(+        Telephony.Sms._ID to id, Telephony.Sms.THREAD_ID to thread, Telephony.Sms.ADDRESS to address,+        Telephony.Sms.BODY to body, Telephony.Sms.DATE to date, Telephony.Sms.TYPE to type,+        Telephony.Sms.READ to read, Telephony.Sms.STATUS to status, Telephony.Sms.SUBSCRIPTION_ID to sub,+    )++    private fun mmsRow(+        id: Long = 5L, thread: Long = 10L, dateSec: Long = 3L,+        box: Int = Telephony.Mms.MESSAGE_BOX_INBOX, read: Int = 0, sub: Int = -1,+    ): Map<String, Any?> = mapOf(+        Telephony.Mms._ID to id, Telephony.Mms.THREAD_ID to thread, Telephony.Mms.DATE to dateSec,+        Telephony.Mms.MESSAGE_BOX to box, Telephony.Mms.READ to read, Telephony.Mms.SUBSCRIPTION_ID to sub,+    )++    // -- contacts --++    @Test+    fun `loadContacts dedupes normalized numbers and skips blanks`() {+        FakeContactsState.phoneRows = listOf(+            mapOf(+                ContactsContract.CommonDataKinds.Phone._ID to 1L,+                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY to "Alice",+                ContactsContract.CommonDataKinds.Phone.NUMBER to "+1 (415) 555-0102",+                ContactsContract.CommonDataKinds.Phone.TYPE to ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,+                ContactsContract.CommonDataKinds.Phone.LABEL to null,+            ),+            mapOf(+                ContactsContract.CommonDataKinds.Phone._ID to 2L,+                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY to "Alice Work",+                ContactsContract.CommonDataKinds.Phone.NUMBER to "+14155550102",+                ContactsContract.CommonDataKinds.Phone.TYPE to ContactsContract.CommonDataKinds.Phone.TYPE_WORK,+                ContactsContract.CommonDataKinds.Phone.LABEL to null,+            ),+            mapOf(+                ContactsContract.CommonDataKinds.Phone._ID to 3L,+                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY to "",+                ContactsContract.CommonDataKinds.Phone.NUMBER to "  ",+                ContactsContract.CommonDataKinds.Phone.TYPE to 0,+                ContactsContract.CommonDataKinds.Phone.LABEL to null,+            ),+            mapOf(+                ContactsContract.CommonDataKinds.Phone._ID to 4L,+                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY to "",+                ContactsContract.CommonDataKinds.Phone.NUMBER to "911",+                ContactsContract.CommonDataKinds.Phone.TYPE to 0,+                ContactsContract.CommonDataKinds.Phone.LABEL to null,+            ),+        )+        val contacts = CommunicateRepository.loadContacts(context)+        assertEquals(2, contacts.size)+        assertEquals("Alice", contacts[0].name)+        assertEquals("+1 (415) 555-0102", contacts[0].phoneNumber)+        assertEquals("911", contacts[1].name) // blank display name falls back to the number+    }++    @Test+    fun `loadContacts returns empty without permission`() {+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_CONTACTS)+        FakeContactsState.phoneRows = listOf(emptyMap())+        assertTrue(CommunicateRepository.loadContacts(context).isEmpty())+    }++    // -- call log --++    @Test+    fun `loadCallLogs maps types and blank numbers`() {+        FakeTelephonyState.callLogRows = listOf(+            mapOf(+                CallLog.Calls._ID to 1L, CallLog.Calls.CACHED_NAME to "Bob",+                CallLog.Calls.NUMBER to "+14155550103", CallLog.Calls.TYPE to CallLog.Calls.INCOMING_TYPE,+                CallLog.Calls.DATE to 5_000L, CallLog.Calls.DURATION to 30L,+                CallLog.Calls.PHONE_ACCOUNT_ID to "99",+            ),+            mapOf(+                CallLog.Calls._ID to 2L, CallLog.Calls.CACHED_NAME to null,+                CallLog.Calls.NUMBER to "", CallLog.Calls.TYPE to CallLog.Calls.MISSED_TYPE,+                CallLog.Calls.DATE to 4_000L, CallLog.Calls.DURATION to 0L,+                CallLog.Calls.PHONE_ACCOUNT_ID to null,+            ),+            mapOf(+                CallLog.Calls._ID to 3L, CallLog.Calls.CACHED_NAME to "  ",+                CallLog.Calls.NUMBER to "123", CallLog.Calls.TYPE to 999,+                CallLog.Calls.DATE to 3_000L, CallLog.Calls.DURATION to 5L,+                CallLog.Calls.PHONE_ACCOUNT_ID to null,+            ),+        )+        val logs = CommunicateRepository.loadCallLogs(context)+        assertEquals(3, logs.size)+        assertEquals(CommunicateCallType.Incoming, logs[0].type)+        assertEquals("Bob", logs[0].displayName)+        assertNull(logs[0].subscriptionId) // 99 is not an active SIM+        assertEquals("Unknown", logs[1].phoneNumber)+        assertEquals(CommunicateCallType.Missed, logs[1].type)+        assertNull(logs[1].displayName)+        assertEquals(CommunicateCallType.Unknown, logs[2].type)+        assertNull(logs[2].displayName)+    }++    @Test+    fun `loadCallLogs returns empty without permission`() {+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_CALL_LOG)+        assertTrue(CommunicateRepository.loadCallLogs(context).isEmpty())+    }++    @Test+    fun `call type mapping covers every provider type`() {+        assertEquals(CommunicateCallType.Incoming, CallLog.Calls.INCOMING_TYPE.toCommunicateCallType())+        assertEquals(CommunicateCallType.Outgoing, CallLog.Calls.OUTGOING_TYPE.toCommunicateCallType())+        assertEquals(CommunicateCallType.Missed, CallLog.Calls.MISSED_TYPE.toCommunicateCallType())+        assertEquals(CommunicateCallType.Rejected, CallLog.Calls.REJECTED_TYPE.toCommunicateCallType())+        assertEquals(CommunicateCallType.Blocked, CallLog.Calls.BLOCKED_TYPE.toCommunicateCallType())+        assertEquals(CommunicateCallType.Voicemail, CallLog.Calls.VOICEMAIL_TYPE.toCommunicateCallType())+        assertEquals(CommunicateCallType.Unknown, (-1).toCommunicateCallType())+    }++    // -- SMS messages --++    @Test+    fun `loadSmsMessages maps direction read and status`() {+        FakeTelephonyState.smsRows = listOf(+            smsRow(id = 1L, type = Telephony.Sms.MESSAGE_TYPE_SENT, status = Telephony.Sms.STATUS_COMPLETE),+            smsRow(id = 2L, type = Telephony.Sms.MESSAGE_TYPE_FAILED, body = "nope"),+            smsRow(id = 3L, type = Telephony.Sms.MESSAGE_TYPE_OUTBOX, status = Telephony.Sms.STATUS_PENDING),+            smsRow(id = 4L, type = Telephony.Sms.MESSAGE_TYPE_INBOX, read = 1, sub = 2),+        )+        val msgs = CommunicateRepository.loadSmsMessages(context, threadId = null)+        assertEquals(4, msgs.size)+        assertTrue(msgs[0].outgoing)+        assertEquals(MessageStatus.Delivered, msgs[0].status)+        assertEquals(MessageStatus.Failed, msgs[1].status)+        assertTrue(msgs[2].outgoing)+        assertEquals(MessageStatus.Sent, msgs[2].status)+        assertFalse(msgs[3].outgoing)+        assertTrue(msgs[3].read)+        assertEquals(MessageStatus.None, msgs[3].status)+        assertEquals(2, msgs[3].subscriptionId)+    }++    @Test+    fun `loadSmsMessages filters by thread and needs permission`() {+        FakeTelephonyState.smsRows = listOf(smsRow(id = 1L, thread = 10L), smsRow(id = 2L, thread = 11L))+        assertEquals(listOf(1L), CommunicateRepository.loadSmsMessages(context, 10L).map { it.id })+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_SMS)+        assertTrue(CommunicateRepository.loadSmsMessages(context, null).isEmpty())+    }++    @Test+    fun `smsStatus precedence failed then delivered then sent`() {+        with(CommunicateRepository) {+            assertEquals(+                MessageStatus.Failed,+                smsStatus(Telephony.Sms.MESSAGE_TYPE_FAILED, outgoing = true, Telephony.Sms.STATUS_COMPLETE))+            assertEquals(+                MessageStatus.None,+                smsStatus(Telephony.Sms.MESSAGE_TYPE_INBOX, outgoing = false, Telephony.Sms.STATUS_COMPLETE))+            assertEquals(+                MessageStatus.Failed,+                smsStatus(Telephony.Sms.MESSAGE_TYPE_SENT, outgoing = true, Telephony.Sms.STATUS_FAILED))+            assertEquals(+                MessageStatus.Sent,+                smsStatus(Telephony.Sms.MESSAGE_TYPE_SENT, outgoing = true, Telephony.Sms.STATUS_NONE))+        }+    }++    // -- MMS messages / parts / sender --++    @Test+    fun `loadMmsMessages joins text image parts and sender`() {+        FakeTelephonyState.mmsRows = listOf(mmsRow(id = 5L), mmsRow(id = 6L, box = Telephony.Mms.MESSAGE_BOX_SENT))+        FakeTelephonyState.partRows = listOf(+            mapOf("_id" to 51L, "ct" to "text/plain", "text" to "mms body", "_data" to null, "mid" to 5L),+            mapOf("_id" to 52L, "ct" to "image/png", "text" to null, "_data" to null, "mid" to 5L),+            mapOf("_id" to 53L, "ct" to "application/smil", "text" to null, "_data" to null, "mid" to 5L),+            mapOf("_id" to 61L, "ct" to "text/plain", "text" to "sent body", "_data" to null, "mid" to 6L),+        )+        FakeTelephonyState.addrRows = listOf(+            mapOf("address" to "+14155550109", "type" to 137),+        )+        val msgs = CommunicateRepository.loadMmsMessages(context, threadId = null)+        assertEquals(2, msgs.size)+        val inbound = msgs[0]+        assertEquals("mms body", inbound.body)+        assertEquals(3_000L, inbound.timestampMillis) // MMS DATE is seconds+        assertEquals("+14155550109", inbound.address)+        assertEquals("+14155550109", inbound.senderAddress)+        assertEquals(1, inbound.attachments.size)+        assertEquals("content://mms/part/52", inbound.attachments[0].contentUri)+        assertEquals("image/png", inbound.attachments[0].mimeType)+        assertTrue(msgs[1].outgoing)+        assertEquals(MessageStatus.Sent, msgs[1].status)+        assertNull(msgs[1].senderAddress)+    }++    @Test+    fun `mms text part stored as file is read through the part uri`() {+        FakeTelephonyState.partRows = listOf(+            mapOf("_id" to 71L, "ct" to "text/plain", "text" to null, "_data" to "/data/part71", "mid" to 7L),+        )+        val (text, attachments) = with(CommunicateRepository) { loadMmsParts(context, 7L) }+        assertEquals("file-body", text)+        assertTrue(attachments.isEmpty())+        assertEquals("file-body", with(CommunicateRepository) { readMmsTextPart(context, 71L) })+    }++    @Test+    fun `loadMmsSender ignores the insert-address token`() {+        FakeTelephonyState.addrRows = listOf(mapOf("address" to "insert-address-token", "type" to 137))+        assertNull(with(CommunicateRepository) { loadMmsSender(context, 5L) })+        FakeTelephonyState.addrRows = listOf(mapOf("address" to "  ", "type" to 137))+        assertNull(with(CommunicateRepository) { loadMmsSender(context, 5L) })+    }++    // -- threads --++    @Test+    fun `loadThreadRecipients resolves canonical addresses`() {+        FakeTelephonyState.canonicalRows = listOf(+            mapOf("_id" to "1", "address" to "+14155550102"),+            mapOf("_id" to "2", "address" to ""),+            mapOf("_id" to "3", "address" to "+14155550103"),+        )+        FakeTelephonyState.threadRows = listOf(+            mapOf(Telephony.Threads._ID to 10L, Telephony.Threads.RECIPIENT_IDS to "1 3"),+            mapOf(Telephony.Threads._ID to 11L, Telephony.Threads.RECIPIENT_IDS to "2"),+        )+        val recipients = with(CommunicateRepository) { loadThreadRecipients(context) }+        assertEquals(listOf("+14155550102", "+14155550103"), recipients[10L])+        assertNull(recipients[11L])+    }++    @Test+    fun `loadSmsThreads merges sms and mms into group and single threads`() {+        FakeTelephonyState.canonicalRows = listOf(+            mapOf("_id" to "1", "address" to "+14155550102"),+            mapOf("_id" to "3", "address" to "+14155550103"),+        )+        FakeTelephonyState.threadRows = listOf(+            mapOf(Telephony.Threads._ID to 10L, Telephony.Threads.RECIPIENT_IDS to "1 3"),+            mapOf(Telephony.Threads._ID to 11L, Telephony.Threads.RECIPIENT_IDS to "1"),+        )+        FakeTelephonyState.smsRows = listOf(+            smsRow(id = 1L, thread = 10L, body = "group latest", date = 9_000L, read = 0),+            smsRow(id = 2L, thread = 10L, body = "group older", date = 8_000L, read = 1),+            smsRow(id = 3L, thread = 11L, body = "single", date = 7_000L, address = "+14155550102"),+        )+        FakeTelephonyState.mmsRows = listOf(mmsRow(id = 5L, thread = 11L, dateSec = 6L))+        FakeTelephonyState.partRows = listOf(+            mapOf("_id" to 61L, "ct" to "text/plain", "text" to "mms single", "_data" to null, "mid" to 5L),+        )+        val threads = CommunicateRepository.loadSmsThreads(context)+        assertEquals(2, threads.size)+        val group = threads.first { it.threadId == 10L }+        assertTrue(group.isGroup)+        assertEquals("group latest", group.snippet)+        assertEquals(1, group.unreadCount)+        assertEquals(listOf("+14155550102", "+14155550103"), group.participants)+        val single = threads.first { it.threadId == 11L }+        assertFalse(single.isGroup)+        assertEquals("+14155550102", single.address)+        assertEquals("single", single.snippet) // newest of SMS (7s) vs MMS (6s)+    }++    @Test+    fun `loadSmsThreads returns empty without sms permission`() {+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_SMS)+        assertTrue(CommunicateRepository.loadSmsThreads(context).isEmpty())+    }++    // -- contact helpers --++    @Test+    fun `findContactName resolves blanks and misses`() {+        FakeContactsState.lookupRows = listOf(+            mapOf(ContactsContract.PhoneLookup.DISPLAY_NAME_PRIMARY to "Alice"),+        )+        assertEquals("Alice", CommunicateRepository.findContactName(context, "+14155550102"))+        assertNull(CommunicateRepository.findContactName(context, " "))+        FakeContactsState.lookupRows = emptyList()+        assertNull(CommunicateRepository.findContactName(context, "+14155550102"))+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_CONTACTS)+        FakeContactsState.lookupRows = listOf(+            mapOf(ContactsContract.PhoneLookup.DISPLAY_NAME_PRIMARY to "Alice"),+        )+        assertNull(CommunicateRepository.findContactName(context, "+14155550102"))+    }++    @Test+    fun `isUnknownContact rejects service ids and known numbers`() {+        assertFalse(CommunicateRepository.isUnknownContact(context, ""))+        assertFalse(CommunicateRepository.isUnknownContact(context, "[email protected]"))+        assertFalse(CommunicateRepository.isUnknownContact(context, "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff"))+        assertFalse(CommunicateRepository.isUnknownContact(context, "service-no-digits"))+        FakeContactsState.lookupRows = listOf(+            mapOf(ContactsContract.PhoneLookup.DISPLAY_NAME_PRIMARY to "Alice"),+        )+        assertFalse(CommunicateRepository.isUnknownContact(context, "+14155550102"))+        FakeContactsState.lookupRows = emptyList()+        assertTrue(CommunicateRepository.isUnknownContact(context, "+14155559999"))+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_CONTACTS)+        assertFalse(CommunicateRepository.isUnknownContact(context, "+14155559999"))+    }++    @Test+    fun `composer intent carries number and body`() {+        CommunicateRepository.openSmsComposer(context, "+14155550102", "hello")+        val intent = shadowOf(context as Application).nextStartedActivity+        assertNotNull(intent)+        assertEquals(android.content.Intent.ACTION_SENDTO, intent.action)+        assertEquals("smsto:+14155550102", intent.data.toString())+        assertEquals("hello", intent.getStringExtra("sms_body"))+    }++    @Test+    fun `markSimThreadRead sums provider updates`() = kotlinx.coroutines.test.runTest {+        FakeTelephonyState.updateResult = 2+        assertTrue(CommunicateRepository.markSimThreadRead(context, 10L))+        assertEquals(2, FakeTelephonyState.updates.size) // SMS + MMS tables+        FakeTelephonyState.updateResult = 0+        assertFalse(CommunicateRepository.markSimThreadRead(context, 10L))+    }++    @Test+    fun `group thread id is null for empty recipient sets`() {+        assertNull(CommunicateRepository.getOrCreateSmsGroupThreadId(context, listOf(" ", "")))+        assertNull(CommunicateRepository.getOrCreateSmsGroupThreadId(context, emptyList()))+    }++    @Test+    fun `phone account handle is null for negative or unpermitted subscriptions`() {+        assertNull(with(CommunicateRepository) { phoneAccountHandleForSub(context, -1) })+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_PHONE_STATE)+        assertNull(with(CommunicateRepository) { phoneAccountHandleForSub(context, 3) })+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave4W1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave4W1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave4W1Test.ktnew file mode 100644index 0000000000..ed776c8852--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave4W1Test.kt@@ -0,0 +1,164 @@+package com.vayunmathur.communicate.data++import android.Manifest+import android.app.Application+import android.content.Context+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.signal.SignalAuthData+import com.vayunmathur.communicate.data.signal.SignalClient+import com.vayunmathur.communicate.data.signal.SignalConversation+import com.vayunmathur.communicate.data.signal.SignalDatabase+import com.vayunmathur.communicate.data.signal.refreshGroup+import com.vayunmathur.communicate.data.signal.setGroupName+import com.vayunmathur.communicate.data.signal.updateGroupParticipants+import com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * W1 wave 4: MMS true-path sends, the uncaptured MEX operation catalog,+ * Signal group-op early returns, and WhatsApp group creation offline.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [W1SmsManagerShadow::class])+class CommunicateWave4W1Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var signalDb: SignalDatabase++    @BeforeTest+    fun setUp() {+        FakeTelephonyState.reset()+        FakeContactsState.reset()+        Robolectric.setupContentProvider(FakeSmsProvider::class.java, "sms")+        Robolectric.setupContentProvider(FakeMmsProvider::class.java, "mms")+        Robolectric.setupContentProvider(FakeMmsSmsProvider::class.java, "mms-sms")+        Robolectric.setupContentProvider(FakeContactsProvider::class.java, android.provider.ContactsContract.AUTHORITY)+        shadowOf(context as Application).grantPermissions(+            Manifest.permission.SEND_SMS,+            Manifest.permission.READ_CONTACTS,+        )+        signalDb = Room.inMemoryDatabaseBuilder(context, SignalDatabase::class.java)+            .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()+        SignalClient.db = signalDb+        SignalClient.authData = SignalAuthData(+            phoneNumber = "+14155552671",+            aci = "3f0e5a2c-1111-2222-3333-444455556666",+            password = "secret",+        )+        SignalClient.socket = null+        SignalClient.unauthSocket = null+        SignalClient.e2e = null+        SignalClient.pendingIdentityChanges.clear()+    }++    @AfterTest+    fun tearDown() {+        SignalClient.db = null+        SignalClient.authData = null+        SignalClient.e2e = null+        SignalClient.pendingIdentityChanges.clear()+        signalDb.close()+    }++    // -- MMS true path --++    @Test+    fun `sendSimMms sends a group text as MMS and persists it`() {+        val ok = with(CommunicateRepository) {+            sendSimMms(context, -1, listOf("+14155550102", "+14155550103"), "group hi", emptyList())+        }+        assertTrue(ok)+        // The outgoing MMS row + text part + TO addresses were persisted.+        val uris = FakeTelephonyState.inserts.map { it.first.toString() }+        assertTrue(uris.any { it == "content://mms" }, "$uris")+        assertTrue(uris.any { it.contains("/addr") }, "$uris")+    }++    // Note: only one true MMS send per Robolectric sandbox โ€” FileProvider+    // caches its path strategy from the first test's data directory, so a+    // second send in another method fails to resolve the PDU uri. The+    // unified group dispatch shares this same sendSimMms path.++    // -- MEX catalog (uncaptured ops fail typed without any network) --++    @Test+    fun `mex uncaptured operations build variables and fail typed`() = runTest {+        val results = listOf(+            "participating" to WhatsAppMexOps.groupParticipatingGroups(context, "[email protected]"),+            "batch" to WhatsAppMexOps.groupBatchQueryById(context, listOf("[email protected]", "[email protected]")),+            "fullSync" to WhatsAppMexOps.primaryContactsFullSync(+                context, listOf("+14155550102"), sessionId = "sess-1", pageIndex = 0, last = true,+            ),+            "usernameCheck" to WhatsAppMexOps.usernameCheck(context, "alice"),+            "blocklistUpdate" to WhatsAppMexOps.updateBlocklistLid(context, "12345@lid", "phone", "+14155550102", "block"),+            "newsletter" to WhatsAppMexOps.newsletter(context, "123@newsletter"),+            "newsletterJoin" to WhatsAppMexOps.newsletterJoinV2(context, "123@newsletter"),+            "newsletterLeave" to WhatsAppMexOps.newsletterLeaveV2(context, "123@newsletter"),+            "getKeys" to WhatsAppMexOps.getMessagingKeys(context, listOf("[email protected]")),+            "setKeysNoAuth" to WhatsAppMexOps.setMessagingKeys(context),+        )+        for ((name, result) in results) {+            assertTrue(result.transportError != null, "$name unexpectedly succeeded: $result")+            assertFalse(result.isSuccess, "$name")+        }+        assertEquals("no_auth", results.last().second.transportError)+        assertTrue(+            results.dropLast(1).all { it.second.transportError!!.startsWith("no_persisted_id:") },+            "$results",+        )+    }++    // -- Signal group ops (early returns) --++    @Test+    fun `signal group ops refuse unknown or keyless groups`() = runTest {+        assertFalse(SignalClient.setGroupName("group:missing", "New name"))+        assertFalse(SignalClient.updateGroupParticipants("group:missing", listOf("a"), "add"))+        assertFalse(SignalClient.refreshGroup("group:missing"))+        signalDb.conversationDao().upsert(+            SignalConversation(chatId = "group:keyless", isGroup = true, name = "Old"),+        )+        assertFalse(SignalClient.setGroupName("group:keyless", "New name"))+        assertFalse(SignalClient.updateGroupParticipants("group:keyless", listOf("a"), "add"))+        assertFalse(SignalClient.refreshGroup("group:keyless"))+        // Removal is refused even with a master key (not implemented yet).+        signalDb.conversationDao().upsert(+            SignalConversation(+                chatId = "group:known", isGroup = true, name = "Team",+                groupMasterKey = ByteArray(32) { 1 }, groupRevision = 3,+            ),+        )+        assertFalse(SignalClient.updateGroupParticipants("group:known", listOf("a"), "remove"))+        // The local name is untouched by every refused change.+        assertEquals("Old", signalDb.conversationDao().getConversation("group:keyless")!!.name)+        assertEquals("Team", signalDb.conversationDao().getConversation("group:known")!!.name)+    }++    @Test+    fun `signal group ops refuse without auth`() = runTest {+        SignalClient.authData = null+        assertFalse(SignalClient.refreshGroup("group:known"))+    }++    // -- WhatsApp group creation offline --++    @Test+    fun `createWhatsAppGroup needs at least one valid JID`() = runTest {+        assertNull(CommunicateRepository.createWhatsAppGroup(context, "Team", emptyList()))+        assertNull(CommunicateRepository.createWhatsAppGroup(context, "Team", listOf(" ", "group:1")))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave8W1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave8W1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave8W1Test.ktnew file mode 100644index 0000000000..31038cfb10--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave8W1Test.kt@@ -0,0 +1,172 @@+package com.vayunmathur.communicate.data++import android.Manifest+import android.app.Application+import android.content.Context+import android.provider.ContactsContract+import android.util.Base64+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.communicate.data.signal.SignalContactSync+import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData+import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase+import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol+import com.vayunmathur.communicate.data.whatsapp.handleRetryReceipt+import com.vayunmathur.communicate.data.whatsapp.sendRetryReceipt+import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * W1 wave 8: Signal contact-sync pure helpers and its offline early+ * return, plus WhatsApp retry-receipt handling for uncached messages.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CommunicateWave8W1Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        FakeContactsState.reset()+        Robolectric.setupContentProvider(FakeContactsProvider::class.java, ContactsContract.AUTHORITY)+        shadowOf(context as Application).grantPermissions(Manifest.permission.READ_CONTACTS)+    }++    @Test+    fun `signal contact sync encoding helpers round trip`() {+        assertEquals(+            "000000034bbc8d96",+            SignalContactSync.e164ToUint64Bytes("+14155550102").joinToString("") { "%02x".format(it) },+        )+        assertEquals(+            "0000000000000000",+            SignalContactSync.e164ToUint64Bytes("no digits").joinToString("") { "%02x".format(it) },+        )+        assertEquals("+14155550102", SignalContactSync.uint64ToE164(14155550102L))+        assertEquals("+0", SignalContactSync.uint64ToE164(0L))+        assertEquals("+442079460958", SignalContactSync.normalizeE164("020 7946 0958", "GB"))+        assertNull(SignalContactSync.normalizeE164("garbage", "US"))+        assertTrue(SignalContactSync.defaultRegion(context).isNotBlank())+    }++    @Test+    fun `signal contact sync reads contacts and returns early on invalid numbers`() = runTest {+        FakeContactsState.phoneRows = listOf(+            mapOf(+                ContactsContract.CommonDataKinds.Phone._ID to 1L,+                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY to "Garbage",+                ContactsContract.CommonDataKinds.Phone.NUMBER to "not a phone",+                ContactsContract.CommonDataKinds.Phone.TYPE to 2,+                ContactsContract.CommonDataKinds.Phone.LABEL to null,+            ),+            mapOf(+                ContactsContract.CommonDataKinds.Phone._ID to 2L,+                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY to "Blank",+                ContactsContract.CommonDataKinds.Phone.NUMBER to " ",+                ContactsContract.CommonDataKinds.Phone.TYPE to 2,+                ContactsContract.CommonDataKinds.Phone.LABEL to null,+            ),+        )+        val contacts = SignalContactSync.readDeviceContacts(context)+        assertEquals(listOf("Garbage" to "not a phone"), contacts)+        val result = SignalContactSync.sync(context)+        assertEquals(1, result.deviceCount)+        assertEquals(0, result.e164Count)+        assertEquals(0, result.onSignalCount)+        assertNull(result.transportError)+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_CONTACTS)+        assertTrue(SignalContactSync.readDeviceContacts(context).isEmpty())+    }+}++/** WhatsApp retry receipts against a Connected-but-dead socket. */+@RunWith(AndroidJUnit4::class)+class CommunicateRetryW1Test {++    private fun b64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)++    private val auth = WhatsAppAuthData(+        phoneNumber = "+15550001", pushName = "Tester", wid = "[email protected]",+        noisePrivateKey = b64(ByteArray(32) { 1 }), noisePublicKey = b64(ByteArray(32) { 2 }),+        identityPrivateKey = b64(ByteArray(32) { 3 }), identityPublicKey = b64(ByteArray(32) { 4 }),+        registrationId = 14, signedPreKeyId = 5,+        signedPreKeyPublic = b64(ByteArray(32) { 5 }), signedPreKeyPrivate = b64(ByteArray(32) { 6 }),+        signedPreKeySignature = b64(ByteArray(64) { 7 }), lid = "12345@lid",+    )++    private lateinit var db: WhatsAppDatabase++    @BeforeTest+    fun setUp() {+        val app = ApplicationProvider.getApplicationContext<Application>()+        db = Room.inMemoryDatabaseBuilder(app, WhatsAppDatabase::class.java)+            .setSingleConnectionPool().allowMainThreadQueries().build()+        WhatsAppClient.appContext = app+        WhatsAppClient.authData = auth+        WhatsAppClient.db = db+        WhatsAppClient.webSocket = WhatsAppSocket(auth)+        WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected+        WhatsAppClient.recentSentDMs.clear()+        WhatsAppClient.retryResendCounts.clear()+        WhatsAppClient.undecryptableTracker.clear()+    }++    @AfterTest+    fun tearDown() {+        WhatsAppClient.stateMutable.value = WhatsAppClient.State.Idle+        WhatsAppClient.webSocket = null+        WhatsAppClient.db = null+        WhatsAppClient.authData = null+    }++    private fun receipt(id: String?, from: String?, participant: String? = null) = WhatsAppProtocol.Node(+        tag = "receipt",+        attrs = buildMap {+            if (id != null) put("id", id)+            if (from != null) put("from", from)+            put("type", "retry")+            if (participant != null) put("participant", participant)+        },+    )++    @Test+    fun `retry receipts for uncached or group messages are dropped`() = runTest {+        // No message id at all.+        WhatsAppClient.handleRetryReceipt(receipt(id = null, from = "[email protected]"))+        // Group retry: not actionable (group resends are not cached).+        WhatsAppClient.handleRetryReceipt(receipt(id = "m1", from = "[email protected]"))+        // 1:1 retry for a message we never cached: nothing to resend.+        WhatsAppClient.handleRetryReceipt(receipt(id = "m2", from = "[email protected]"))+        WhatsAppClient.handleRetryReceipt(+            receipt(id = "m3", from = "[email protected]", participant = "15550002:[email protected]"),+        )+    }++    @Test+    fun `sendRetryReceipt counts attempts and still sends without keys`() = runTest {+        val node = WhatsAppProtocol.Node(+            tag = "message",+            attrs = mapOf("id" to "in-1", "from" to "[email protected]", "type" to "text"),+        )+        WhatsAppClient.sendRetryReceipt(node)+        // Second receipt attaches keys (the Rust key build fails soft here).+        WhatsAppClient.sendRetryReceipt(node)+        WhatsAppClient.sendRetryReceipt(+            WhatsAppProtocol.Node(tag = "message", attrs = mapOf("from" to "[email protected]")),+        ) // no id: dropped+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave9W1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave9W1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave9W1Test.ktnew file mode 100644index 0000000000..f055f872b5--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWave9W1Test.kt@@ -0,0 +1,126 @@+package com.vayunmathur.communicate.data++import android.content.Context+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.signal.SignalAuthData+import com.vayunmathur.communicate.data.signal.SignalCachedMessage+import com.vayunmathur.communicate.data.signal.SignalClient+import com.vayunmathur.communicate.data.signal.SignalDatabase+import com.vayunmathur.communicate.data.signal.SignalEvent+import com.vayunmathur.communicate.data.signal.markRead+import com.vayunmathur.communicate.data.signal.sendTyping+import com.vayunmathur.communicate.ui.rememberLineChoices+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.async+import kotlinx.coroutines.flow.filterIsInstance+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.withTimeoutOrNull+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * W1 wave 9 (micro): per-line call routing in `CommunicateRepositoryHelperKt`,+ * Signal typing/read-receipt emitters, and the line-choices composition.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CommunicateWave9W1Test {++    @get:Rule+    val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private lateinit var signalDb: SignalDatabase+    private val aci = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff"++    @BeforeTest+    fun setUp() {+        signalDb = Room.inMemoryDatabaseBuilder(context, SignalDatabase::class.java)+            .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()+        SignalClient.db = signalDb+        SignalClient.authData = SignalAuthData(+            phoneNumber = "+14155552671",+            aci = "3f0e5a2c-1111-2222-3333-444455556666",+            password = "secret",+        )+        SignalClient.socket = null+        SignalClient.unauthSocket = null+        SignalClient.e2e = null+        SignalClient.pendingIdentityChanges.clear()+    }++    @AfterTest+    fun tearDown() {+        SignalClient.db = null+        SignalClient.authData = null+        SignalClient.e2e = null+        SignalClient.pendingIdentityChanges.clear()+        signalDb.close()+    }++    @Test+    fun `placeCallForLine routes per line`() = runTest {+        with(CommunicateRepository) {+            assertTrue(placeCallForLine(context, CommunicateLine.Sim, "+14155550102", null))+            assertTrue(placeCallForLine(context, CommunicateLine.GoogleVoice, "+14155550102", null))+            assertFalse(placeCallForLine(context, CommunicateLine.WhatsApp, " ", null))+            assertFalse(placeCallForLine(context, CommunicateLine.WhatsApp, "", ""))+            assertTrue(+                placeCallForLine(context, CommunicateLine.WhatsApp, "+14155550102", null),+            ) // manager is unbridged on this host; routing still reports placed+            assertFalse(placeCallForLine(context, CommunicateLine.Signal, " ", null))+            assertTrue(placeCallForLine(context, CommunicateLine.Signal, "+14155550102", null))+            assertFalse(+                placeCallForLine(context, CommunicateLine.Signal, "+14155550102", "group:unknown"),+            )+            assertFalse(placeCallForLine(context, CommunicateLine.Rcs, "+14155550102", null))+            // WhatsApp/Signal call-control pass-throughs are inert unbridged.+            whatsAppAnswerCall()+            whatsAppRejectCall()+            whatsAppHangupCall()+            whatsAppSetCallMuted(true)+            whatsAppSetCallSpeaker(true)+            assertNotNull(whatsAppCallState.value)+        }+    }++    @Test+    fun `signal typing and markRead emit events and update the cache`() = runTest {+        signalDb.cachedMessageDao().upsert(+            SignalCachedMessage(+                messageId = "m1", conversationId = aci, body = "hi",+                timestamp = 1_700_000_000_000L, outgoing = false, senderId = aci, status = 1,+            ),+        )+        val typing = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined).async { SignalClient.events.filterIsInstance<SignalEvent.TypingIndicator>().first() }+        SignalClient.sendTyping(aci, isTyping = true)+        assertEquals(true, withTimeoutOrNull(5_000) { typing.await() }?.isTyping)+        val receipt = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined).async { SignalClient.events.filterIsInstance<SignalEvent.ReadReceipt>().first() }+        SignalClient.markRead(aci, listOf("m1", "missing"))+        assertNotNull(receipt.await())+        assertEquals(3, signalDb.cachedMessageDao().get("m1")!!.status) // read+        assertFalse(SignalClient.isConnected())+    }++    @Test+    fun `line choices fall back to a single sim when signed out`() {+        var captured: List<LineChoice>? = null+        rule.setContent { captured = rememberLineChoices() }+        rule.waitForIdle()+        val choices = captured+        assertTrue(choices != null && choices.isNotEmpty())+        assertTrue(choices!!.all { it is LineChoice.Sim })+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWhatsAppChatsW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWhatsAppChatsW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWhatsAppChatsW1Test.ktnew file mode 100644index 0000000000..3fe42340e4--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWhatsAppChatsW1Test.kt@@ -0,0 +1,190 @@+package com.vayunmathur.communicate.data++import android.app.Application+import android.util.Base64+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.protobuf.ByteString+import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData+import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient+import com.vayunmathur.communicate.data.whatsapp.WhatsAppConversation+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase+import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol+import com.vayunmathur.communicate.data.whatsapp.expandAppStateKeys+import com.vayunmathur.communicate.data.whatsapp.applyAppStateRecord+import com.vayunmathur.communicate.data.whatsapp.deleteChat+import com.vayunmathur.communicate.data.whatsapp.deleteThread+import com.vayunmathur.communicate.data.whatsapp.markChatUnread+import com.vayunmathur.communicate.data.whatsapp.sendNewThread+import com.vayunmathur.communicate.data.whatsapp.setMute+import com.vayunmathur.communicate.data.whatsapp.storeAppStateKey+import com.vayunmathur.communicate.data.whatsapp.togglePin+import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket+import javax.crypto.Cipher+import javax.crypto.spec.IvParameterSpec+import javax.crypto.spec.SecretKeySpec+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppAppStateProto++/**+ * W1 wave 7: WhatsApp chat housekeeping (`WhatsAppClientChatsKt`) and+ * app-state action application (`WhatsAppClientSyncKt`), against an+ * in-memory database with a Connected-but-dead socket: the sync patches+ * are attempted, and the local store updates still land.+ */+@RunWith(AndroidJUnit4::class)+class CommunicateWhatsAppChatsW1Test {++    private fun b64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)++    private val auth = WhatsAppAuthData(+        phoneNumber = "+15550001", pushName = "Tester", wid = "[email protected]",+        noisePrivateKey = b64(ByteArray(32) { 1 }), noisePublicKey = b64(ByteArray(32) { 2 }),+        identityPrivateKey = b64(ByteArray(32) { 3 }), identityPublicKey = b64(ByteArray(32) { 4 }),+        registrationId = 14, signedPreKeyId = 5,+        signedPreKeyPublic = b64(ByteArray(32) { 5 }), signedPreKeyPrivate = b64(ByteArray(32) { 6 }),+        signedPreKeySignature = b64(ByteArray(64) { 7 }), lid = "12345@lid",+    )++    private lateinit var db: WhatsAppDatabase+    private val jid = "[email protected]"++    @BeforeTest+    fun setUp() {+        val app = ApplicationProvider.getApplicationContext<Application>()+        db = Room.inMemoryDatabaseBuilder(app, WhatsAppDatabase::class.java)+            .setSingleConnectionPool().allowMainThreadQueries().build()+        WhatsAppClient.appContext = app+        WhatsAppClient.authData = auth+        WhatsAppClient.db = db+        WhatsAppClient.webSocket = WhatsAppSocket(auth)+        WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected+        WhatsAppClient.nameCache.clear()+    }++    @AfterTest+    fun tearDown() {+        WhatsAppClient.stateMutable.value = WhatsAppClient.State.Idle+        WhatsAppClient.webSocket = null+        WhatsAppClient.db = null+        WhatsAppClient.authData = null+    }++    private fun encryptedRecord(+        keyId: ByteArray, keyData: ByteArray, plain: ByteArray,+    ): WhatsAppAppStateProto.SyncdRecord {+        val expanded = WhatsAppProtocol.expandAppStateKeys(keyData)+        val iv = ByteArray(16) { it.toByte() }+        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")+        cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(expanded[1], "AES"), IvParameterSpec(iv))+        val blob = iv + cipher.doFinal(plain) + ByteArray(32)+        return WhatsAppAppStateProto.SyncdRecord.newBuilder()+            .setKeyId(WhatsAppAppStateProto.KeyId.newBuilder().setId(ByteString.copyFrom(keyId)))+            .setValue(WhatsAppAppStateProto.SyncdValue.newBuilder().setBlob(ByteString.copyFrom(blob)))+            .build()+    }++    private suspend fun applyAction(index: String, value: WhatsAppAppStateProto.SyncActionValue) {+        val keyId = byteArrayOf(42, 42)+        val keyData = ByteArray(32) { (it * 7 + 1).toByte() }+        WhatsAppClient.storeAppStateKey(keyId, keyData)+        val action = WhatsAppAppStateProto.SyncActionData.newBuilder()+            .setIndex(ByteString.copyFrom(index.toByteArray()))+            .setValue(value)+            .build()+        WhatsAppClient.applyAppStateRecord(encryptedRecord(keyId, keyData, action.toByteArray()), isSet = true)+    }++    @Test+    fun `mute and pin land in the local conversation row`() = runTest {+        db.conversationDao().upsert(WhatsAppConversation(chatJid = jid, lastMessageTimestamp = 99L))+        WhatsAppClient.setMute(jid, muteUntilMs = 777_000L)+        assertEquals(777_000L, db.conversationDao().getConversation(jid)!!.muteEndTime)+        WhatsAppClient.togglePin(jid, pinned = true)+        assertTrue(db.conversationDao().getConversation(jid)!!.pinned)+        WhatsAppClient.togglePin(jid, pinned = false)+        assertTrue(!db.conversationDao().getConversation(jid)!!.pinned)+        WhatsAppClient.markChatUnread(jid, unread = true) // patch attempted; no local flag+        // Unknown conversations are tolerated (nothing to update).+        WhatsAppClient.setMute("[email protected]", 1L)+        WhatsAppClient.togglePin("[email protected]", true)+        assertNull(db.conversationDao().getConversation("[email protected]"))+    }++    @Test+    fun `deleteChat and deleteThread remove the local row`() = runTest {+        db.conversationDao().upsert(WhatsAppConversation(chatJid = jid, lastMessageTimestamp = 99L))+        assertTrue(WhatsAppClient.deleteChat(jid, leaveGroup = false))+        assertNull(db.conversationDao().getConversation(jid))+        db.conversationDao().upsert(WhatsAppConversation(chatJid = "[email protected]", isGroup = true))+        assertTrue(WhatsAppClient.deleteChat("[email protected]", leaveGroup = true))+        assertNull(db.conversationDao().getConversation("[email protected]"))+        db.conversationDao().upsert(WhatsAppConversation(chatJid = jid))+        assertTrue(WhatsAppClient.deleteThread("wa:$jid"))+        assertNull(db.conversationDao().getConversation(jid))+        // The repository delete route uses the same client path.+        db.conversationDao().upsert(WhatsAppConversation(chatJid = jid))+        val thread = SmsThread(+            threadId = 1L, address = "+15550002", displayName = null, snippet = "",+            timestampMillis = 0L, unreadCount = 0, line = CommunicateLine.WhatsApp, remoteId = jid,+        )+        assertTrue(CommunicateRepository.deleteConversation(ApplicationProvider.getApplicationContext(), thread))+        assertNull(db.conversationDao().getConversation(jid))+    }++    @Test+    fun `sendNewThread cannot build without a session`() = runTest {+        assertNull(WhatsAppClient.sendNewThread(jid, "hello"))+        assertNull(WhatsAppClient.sendNewThread("15550003", "hello"))+    }++    @Test+    fun `app state actions update mute pin archive and read flags`() = runTest {+        db.conversationDao().upsert(WhatsAppConversation(chatJid = jid))+        applyAction(+            """["mute","$jid"]""",+            WhatsAppAppStateProto.SyncActionValue.newBuilder()+                .setMuteAction(WhatsAppAppStateProto.MuteAction.newBuilder().setMuteEndTimestamp(4242L))+                .build(),+        )+        assertEquals(4242L, db.conversationDao().getConversation(jid)!!.muteEndTime)+        applyAction(+            """["pin_v1","$jid"]""",+            WhatsAppAppStateProto.SyncActionValue.newBuilder()+                .setPinAction(WhatsAppAppStateProto.PinAction.newBuilder().setPinned(true))+                .build(),+        )+        assertTrue(db.conversationDao().getConversation(jid)!!.pinned)+        applyAction(+            """["archive","$jid"]""",+            WhatsAppAppStateProto.SyncActionValue.newBuilder()+                .setArchiveChatAction(WhatsAppAppStateProto.ArchiveChatAction.newBuilder().setArchived(true))+                .build(),+        )+        assertTrue(db.conversationDao().getConversation(jid)!!.archived)+        applyAction(+            """["markChatAsRead","$jid"]""",+            WhatsAppAppStateProto.SyncActionValue.newBuilder()+                .setMarkChatAsReadAction(WhatsAppAppStateProto.MarkChatAsReadAction.newBuilder().setRead(false))+                .build(),+        )+        assertTrue(db.conversationDao().getConversation(jid)!!.markedAsUnread)+        // An unknown action and an empty index change nothing.+        val before = db.conversationDao().getConversation(jid)+        applyAction(+            """["unknown_action","$jid"]""",+            WhatsAppAppStateProto.SyncActionValue.newBuilder().build(),+        )+        assertEquals(before, db.conversationDao().getConversation(jid))+        assertNotNull(before)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWhatsAppGroupsW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWhatsAppGroupsW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWhatsAppGroupsW1Test.ktnew file mode 100644index 0000000000..9855b83fa4--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CommunicateWhatsAppGroupsW1Test.kt@@ -0,0 +1,89 @@+package com.vayunmathur.communicate.data++import android.app.Application+import android.content.Context+import android.util.Base64+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData+import com.vayunmathur.communicate.data.whatsapp.WhatsAppClient+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase+import com.vayunmathur.communicate.data.whatsapp.enrichGroupFromMex+import com.vayunmathur.communicate.data.whatsapp.fetchAndEmitGroupInfo+import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertNull+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith++/**+ * W1 wave 5: WhatsApp group-info paths in `WhatsAppClientGroupsKt` with a+ * Connected-but-dead socket โ€” IQ waits fail fast and MEX enrichment aborts,+ * and group creation through the repository returns null.+ */+@RunWith(AndroidJUnit4::class)+class CommunicateWhatsAppGroupsW1Test {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun b64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)++    private val auth = WhatsAppAuthData(+        phoneNumber = "+15550001", pushName = "Tester", wid = "[email protected]",+        noisePrivateKey = b64(ByteArray(32) { 1 }), noisePublicKey = b64(ByteArray(32) { 2 }),+        identityPrivateKey = b64(ByteArray(32) { 3 }), identityPublicKey = b64(ByteArray(32) { 4 }),+        registrationId = 14, signedPreKeyId = 5,+        signedPreKeyPublic = b64(ByteArray(32) { 5 }), signedPreKeyPrivate = b64(ByteArray(32) { 6 }),+        signedPreKeySignature = b64(ByteArray(64) { 7 }), lid = "12345@lid",+    )++    private lateinit var db: WhatsAppDatabase++    @BeforeTest+    fun setUp() {+        val app = ApplicationProvider.getApplicationContext<Application>()+        db = Room.inMemoryDatabaseBuilder(app, WhatsAppDatabase::class.java)+            .setSingleConnectionPool().allowMainThreadQueries().build()+        WhatsAppClient.appContext = app+        WhatsAppClient.authData = auth+        WhatsAppClient.db = db+        WhatsAppClient.webSocket = WhatsAppSocket(auth)+        WhatsAppClient.stateMutable.value = WhatsAppClient.State.Connected+        WhatsAppClient.knownGroups.clear()+        WhatsAppClient.pendingMessageIDs.clear()+    }++    @AfterTest+    fun tearDown() {+        WhatsAppClient.stateMutable.value = WhatsAppClient.State.Idle+        WhatsAppClient.webSocket = null+        WhatsAppClient.db = null+        WhatsAppClient.authData = null+        WhatsAppClient.knownGroups.clear()+    }++    @Test+    fun `group info fetch ignores non-group JIDs and fails fast for groups`() = runTest {+        WhatsAppClient.fetchAndEmitGroupInfo("[email protected]") // not a group: no-op+        WhatsAppClient.fetchAndEmitGroupInfo("[email protected]") // IQ unanswered: fails fast+        // A second call for the same group is not suppressed after failure.+        WhatsAppClient.fetchAndEmitGroupInfo("[email protected]")+    }++    @Test+    fun `mex group enrichment aborts when the query fails`() = runTest {+        WhatsAppClient.enrichGroupFromMex("[email protected]", participantCount = 3)+    }++    @Test+    fun `repository group creation returns null when the IQ is unanswered`() = runTest {+        assertNull(+            CommunicateRepository.createWhatsAppGroup(+                context, "Team", listOf("+14155550102", "4155550103", "+14155550102"),+            ),+        )+    }+}
communicate/src/test/java/com/vayunmathur/communicate/signal/SignalInboundPollW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalInboundPollW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalInboundPollW1Test.ktnew file mode 100644index 0000000000..d6d9481800--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalInboundPollW1Test.kt@@ -0,0 +1,209 @@+package com.vayunmathur.communicate.signal++import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.google.protobuf.ByteString+import com.vayunmathur.communicate.data.signal.SignalAuthData+import com.vayunmathur.communicate.data.signal.SignalCachedMessage+import com.vayunmathur.communicate.data.signal.SignalClient+import com.vayunmathur.communicate.data.signal.SignalDatabase+import com.vayunmathur.communicate.data.signal.SignalEvent+import com.vayunmathur.communicate.data.signal.SignalProtocol+import com.vayunmathur.communicate.data.signal.SignalServiceData+import com.vayunmathur.communicate.data.signal.e2e.SignalE2E+import com.vayunmathur.communicate.data.signal.e2e.ensureLocalPreKeys+import com.vayunmathur.communicate.data.signal.handleInboundFrame+import com.vayunmathur.communicate.data.signal.registration.SignalRegistrationKeys+import com.vayunmathur.communicate.data.signal.SignalPollOptionData+import com.vayunmathur.communicate.data.signal.transport.SignalPayload+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.withTimeoutOrNull+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.whispersystems.signalservice.internal.push.SignalServiceProtos+import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage+import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketRequestMessage++/**+ * W1 wave 5: Signal inbound poll create/vote/terminate and quoted text,+ * through the real E2E inbound frame path (Alice under test, Bob as peer).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SignalInboundPollW1Test {++    private lateinit var db: SignalDatabase+    private lateinit var authA: SignalAuthData+    private lateinit var authB: SignalAuthData+    private lateinit var alice: SignalE2E+    private lateinit var bob: SignalE2E++    private val bobAci = "7c1d9b4e-aaaa-bbbb-cccc-ddddeeeeffff"++    @BeforeTest+    fun setUp() {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        db = Room.inMemoryDatabaseBuilder(ctx, SignalDatabase::class.java)+            .setDriver(BundledSQLiteDriver()).allowMainThreadQueries().build()+        authA = SignalRegistrationKeys.generate("+14155552671").authScaffold.copy(+            aci = "3f0e5a2c-1111-2222-3333-444455556666",+        )+        authB = SignalRegistrationKeys.generate("+14155550000").authScaffold.copy(aci = bobAci)+        alice = SignalE2E(db, authA)+        bob = SignalE2E(db, authB)+        SignalClient.db = db+        SignalClient.authData = authA+        SignalClient.e2e = alice+        SignalClient.socket = null+        SignalClient.unauthSocket = null+        SignalClient.pendingIdentityChanges.clear()+    }++    @AfterTest+    fun tearDown() {+        SignalClient.db = null+        SignalClient.authData = null+        SignalClient.e2e = null+        SignalClient.pendingIdentityChanges.clear()+        db.close()+    }++    private fun bobBundleForAlice(): SignalE2E.ParsedPreKeyBundle {+        val upload = bob.ensureLocalPreKeys()+        val signed = upload.signedPreKey ?: error("no signed prekey")+        val kyber = upload.lastResortKyber ?: error("no kyber prekey")+        return SignalE2E.ParsedPreKeyBundle(+            registrationId = authB.effectiveAciRegId(),+            preKeyId = upload.oneTimeEcPreKeys.firstOrNull()?.id,+            preKeyPublic = upload.oneTimeEcPreKeys.firstOrNull()?.publicKey,+            signedPreKeyId = signed.id,+            signedPreKeyPublic = signed.publicKey,+            signedPreKeySignature = signed.signature ?: ByteArray(0),+            identityKey = android.util.Base64.decode(authB.effectiveAciPublic(), android.util.Base64.NO_WRAP),+            kyberPreKeyId = kyber.id,+            kyberPreKeyPublic = kyber.publicKey,+            kyberPreKeySignature = kyber.signature ?: ByteArray(0),+        )+    }++    private fun wsFrame(content: ByteArray, timestamp: Long): ByteArray {+        val envelope = SignalServiceProtos.Envelope.newBuilder()+            .setType(SignalServiceProtos.Envelope.Type.DOUBLE_RATCHET)+            .setSourceServiceId(bobAci)+            .setSourceDeviceId(1)+            .setClientTimestamp(timestamp)+            .setContent(ByteString.copyFrom(content))+            .build()+        return WebSocketMessage.newBuilder()+            .setType(WebSocketMessage.Type.REQUEST)+            .setRequest(+                WebSocketRequestMessage.newBuilder().setVerb("PUT").setPath("/api/v1/message")+                    .setId(99L).setBody(ByteString.copyFrom(envelope.toByteArray())).build(),+            ).build().toByteArray()+    }++    /** Encrypt a Content payload Bob->Alice on their established session and feed it inbound. */+    private suspend fun feedFromBob(content: SignalServiceProtos.Content, timestamp: Long): SignalEvent? {+        if (!alice.hasSession(bobAci, 1)) {+            alice.processPreKeyBundle(bobAci, 1, bobBundleForAlice())+        }+        val paddedBytes = SignalProtocol.padMessageBody(content.toByteArray())+        // Establish the session Alice-side, then re-encrypt Bob->Alice so+        // decryptEnvelope can open it as a session (DOUBLE_RATCHET) message.+        val enc = alice.encryptDM(bobAci, 1, paddedBytes)+        bob.decryptDM(authA.aci, 1, isPreKey = true, ciphertext = enc.data)+        val back = bob.encryptDM(authA.aci, 1, paddedBytes)+        val deferred = CoroutineScope(Dispatchers.Unconfined).async { SignalClient.events.first() }+        SignalClient.handleInboundFrame(wsFrame(back.data, timestamp))+        return withTimeoutOrNull(5_000) { deferred.await() }+    }++    private fun content(dm: SignalServiceProtos.DataMessage): SignalServiceProtos.Content =+        SignalServiceProtos.Content.newBuilder().setDataMessage(dm).build()++    @Test+    fun `inbound poll create emits the poll as an incoming message`() = runTest {+        val dm = SignalPayload.buildDataMessage(+            body = "Lunch?",+            timestamp = 1_700_000_000_000L,+            pollCreate = SignalPayload.buildPollCreate("Lunch?", listOf("Pizza", "Sushi")),+        )+        val event = feedFromBob(content(dm), 1_700_000_000_000L)+        assertTrue(event is SignalEvent.IncomingMessage, "got $event")+        val incoming = event as SignalEvent.IncomingMessage+        assertEquals("Lunch?", incoming.pollQuestion)+        assertEquals(listOf("Pizza", "Sushi"), incoming.pollOptions)+        assertEquals(bobAci, incoming.senderId)+    }++    @Test+    fun `inbound poll vote resolves option names from the cached poll`() = runTest {+        val pollTs = 1_700_000_100_000L+        db.cachedMessageDao().upsert(+            SignalCachedMessage(+                messageId = "poll-1",+                conversationId = bobAci,+                body = "Lunch?",+                timestamp = pollTs,+                outgoing = false,+                senderId = bobAci,+                serviceData = SignalServiceData(+                    pollQuestion = "Lunch?",+                    pollOptions = listOf(SignalPollOptionData("Pizza"), SignalPollOptionData("Sushi")),+                    senderId = bobAci,+                ).serialize(),+            ),+        )+        val dm = SignalPayload.buildDataMessage(+            body = "",+            timestamp = pollTs + 1_000L,+            pollVote = SignalPayload.buildPollVote(targetSentTimestamp = pollTs, optionIndexes = listOf(1)),+        )+        val event = feedFromBob(content(dm), pollTs + 1_000L)+        assertTrue(event is SignalEvent.PollVote, "got $event")+        val vote = event as SignalEvent.PollVote+        assertEquals(listOf("Sushi"), vote.optionNames)+        assertEquals(bobAci, vote.voterId)+    }++    @Test+    fun `inbound poll terminate arrives as a generic incoming update`() = runTest {+        val terminate = SignalServiceProtos.DataMessage.PollTerminate.newBuilder()+            .setTargetSentTimestamp(1_700_000_100_000L)+            .build()+        val dm = SignalServiceProtos.DataMessage.newBuilder()+            .setTimestamp(1_700_000_200_000L)+            .setPollTerminate(terminate)+            .build()+        val event = feedFromBob(content(dm), 1_700_000_200_000L)+        assertNotNull(event, "poll terminate should not be dropped")+    }++    @Test+    fun `inbound quoted text carries the quote through`() = runTest {+        val quote = SignalServiceProtos.DataMessage.Quote.newBuilder()+            .setId(1_700_000_000_000L)+            .setText("original")+            .build()+        val dm = SignalServiceProtos.DataMessage.newBuilder()+            .setBody("replying to you")+            .setTimestamp(1_700_000_300_000L)+            .setQuote(quote)+            .build()+        val event = feedFromBob(content(dm), 1_700_000_300_000L)+        assertTrue(event is SignalEvent.IncomingMessage, "got $event")+        assertEquals("replying to you", (event as SignalEvent.IncomingMessage).body)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/ui/CommunicateScreensW1Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/ui/CommunicateScreensW1Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/ui/CommunicateScreensW1Test.ktnew file mode 100644index 0000000000..c88766815d--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/ui/CommunicateScreensW1Test.kt@@ -0,0 +1,230 @@+package com.vayunmathur.communicate.ui++import android.content.Context+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.CommunicateAttachment+import com.vayunmathur.communicate.data.CommunicateCallLogEntry+import com.vayunmathur.communicate.data.CommunicateCallType+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.MessageStatus+import com.vayunmathur.communicate.data.SmsMessage+import com.vayunmathur.communicate.data.whatsapp.Reaction+import com.vayunmathur.communicate.data.whatsapp.WhatsAppServiceData+import java.util.concurrent.CopyOnWriteArrayList+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * W1: Compose coverage for `CallLogsScreenKt` (content rows + delete confirm),+ * `ConversationMessageBubbleKt` (bubbles, ticks, quotes, polls, reactions) and+ * the pure number/region helpers in `NewMessagePickerKt`.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CommunicateScreensW1Test {++    @get:Rule+    val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun entry(+        id: Long, name: String?, number: String, type: CommunicateCallType, duration: Long = 65L,+    ) = CommunicateCallLogEntry(+        id = id, displayName = name, phoneNumber = number, type = type,+        timestampMillis = 1_785_566_000_000L, durationSeconds = duration,+        line = if (id % 2L == 0L) CommunicateLine.GoogleVoice else CommunicateLine.Sim,+    )++    @Test+    fun `call logs content renders every call type and routes clicks`() {+        val called = CopyOnWriteArrayList<CommunicateCallLogEntry>()+        val entries = listOf(+            entry(1L, "Alice", "+14155550102", CommunicateCallType.Incoming),+            entry(2L, null, "+14155550103", CommunicateCallType.Missed, duration = 0L),+            entry(3L, "Carol", "+14155550104", CommunicateCallType.Outgoing, duration = 3_661L),+            entry(4L, null, "+14155550105", CommunicateCallType.Rejected, duration = 5L),+            entry(5L, "Eve", "+14155550106", CommunicateCallType.Blocked, duration = 125L),+            entry(6L, null, "+14155550107", CommunicateCallType.Voicemail, duration = 9L),+            entry(7L, "Gus", "+14155550108", CommunicateCallType.Unknown, duration = 60L),+        )+        rule.setContent { CallLogsContent(entries = entries, onCall = { called += it }, onDelete = {}) }+        rule.onNodeWithText("Alice").assertIsDisplayed()+        rule.onNodeWithText("+14155550103").assertIsDisplayed()+        rule.onNodeWithText("Carol").performClick()+        rule.waitForIdle()+        assertEquals(listOf(3L), called.map { it.id })+    }++    @Test+    fun `call logs delete flows through the confirm dialog`() {+        val deleted = CopyOnWriteArrayList<CommunicateCallLogEntry>()+        val entries = listOf(entry(1L, "Alice", "+14155550102", CommunicateCallType.Incoming))+        rule.setContent { CallLogsContent(entries = entries, onCall = {}, onDelete = { deleted += it }) }+        // Overflow menu -> Delete -> confirm. The overflow button is the+        // last clickable in the row (row, call button, overflow).+        rule.onNodeWithText("Alice").assertIsDisplayed()+        val clickables = rule.onAllNodes(androidx.compose.ui.test.hasClickAction())+        clickables[clickables.fetchSemanticsNodes().size - 1].performClick()+        rule.waitForIdle()+        rule.onNodeWithText("Delete").performClick()+        rule.waitForIdle()+        rule.onNodeWithText("Delete").performClick()+        rule.waitForIdle()+        assertEquals(listOf(1L), deleted.map { it.id })+    }++    private fun message(+        body: String = "hello", outgoing: Boolean = true, line: CommunicateLine = CommunicateLine.Sim,+        status: MessageStatus = MessageStatus.None, serviceData: String? = null,+        senderAddress: String? = null, attachments: List<CommunicateAttachment> = emptyList(),+    ) = SmsMessage(+        id = 1L, threadId = 1L, address = "+14155550102", body = body,+        timestampMillis = 1_785_566_000_000L, outgoing = outgoing, read = true,+        line = line, serviceData = serviceData, senderAddress = senderAddress,+        status = status, attachments = attachments,+    )++    @Test+    fun `message bubble renders outgoing text`() {+        rule.setContent { MessageBubble(message(outgoing = true)) }+        rule.onNodeWithText("hello").assertIsDisplayed()+    }++    @Test+    fun `message bubble renders incoming text`() {+        rule.setContent { MessageBubble(message(body = "reply", outgoing = false)) }+        rule.onNodeWithText("reply").assertIsDisplayed()+    }++   

Diff truncated.