Modern Apps git

← Modern-Apps.git

communicate: add tests for slice 4/6 (googlevoice, car, call, telephony)

Commit
53025d5a6cdfca226fb0051a81ee06284cf061ae
Author
Vayun Mathur <[email protected]>
When
2026-11-06 18:40 UTC (29 days ago)
Parents
74d67b6
Slice 4/6 (googlevoice/, service/car/, call paths, telephony non-RCS,
notifications, ui/call): 24 test files, ~200 tests (JVM + Robolectric).

Scope aggregate ~41% instruction coverage (36/72 classes >= 85%; pure-logic
classes mostly >= 90-100%: parsers, SIP messages, session, MMS PDU,
registries, monogram/controls). Remainder is Android-framework bound and
not honestly reachable on the JVM in this pass: car screens, InAppCall
video/screen UI, GV network client/web sender, foreground/in-call
services, WebRTC audio, SipClient socket paths, sync services, deliver
receivers, SimCallBridge modem callbacks, GV sign-in screen, bubble
activity. Compose status/duration/controls and telecom lifecycle are
covered; bridge async projection and video pipelines are not.

(cherry picked from commit f269cc296eb5810c4e6b80452cb85a60bd5eedb7)

Diff

communicate/src/test/java/com/vayunmathur/communicate/data/InAppCallRegistrySlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/InAppCallRegistrySlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/InAppCallRegistrySlice4Test.ktnew file mode 100644index 0000000000..33ed0bc29e--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/InAppCallRegistrySlice4Test.kt@@ -0,0 +1,304 @@+package com.vayunmathur.communicate.data++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.call.CallCapabilities+import com.vayunmathur.communicate.data.call.InAppCallController+import com.vayunmathur.communicate.data.call.InAppCallDtmfController+import com.vayunmathur.communicate.data.call.InAppCallHoldController+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.data.call.isLiveCall+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 org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the shared in-app call state machine ([InAppCallRegistry]).+ *+ * Robolectric (the registry logs through `android.util.Log`). Asserts the phase+ * lifecycle, capability presets, controller fan-out and the video/screenshare+ * guards — the contract every calling line depends on.+ */+@RunWith(RobolectricTestRunner::class)+class InAppCallRegistrySlice4Test {++    private val actions = mutableListOf<String>()++    private val controller = object : InAppCallController {+        override fun answer() { actions.add("answer") }+        override fun reject() { actions.add("reject") }+        override fun hangup() { actions.add("hangup") }+        override fun setMuted(muted: Boolean) { actions.add("muted=$muted") }+        override fun setSpeaker(on: Boolean) { actions.add("speaker=$on") }+    }++    private val dtmf = object : InAppCallDtmfController {+        override fun sendDtmf(digit: String) { actions.add("dtmf=$digit") }+    }++    private val hold = object : InAppCallHoldController {+        override fun setHeld(held: Boolean) { actions.add("held=$held") }+    }++    @BeforeTest+    fun setUp() {+        ApplicationProvider.getApplicationContext<android.content.Context>()+        actions.clear()+        // Reset the singleton: end any leaked call, then clear the terminal state.+        InAppCallRegistry.onEnded("reset")+        InAppCallRegistry.clearEnded()+        InAppCallRegistry.videoController = null+        InAppCallRegistry.dtmfController = null+        InAppCallRegistry.holdController = null+        InAppCallRegistry.connection = null+    }++    private fun startOutgoing(+        caps: CallCapabilities = CallCapabilities.AudioOnly,+        line: CommunicateLine = CommunicateLine.Sim,+    ) {+        InAppCallRegistry.bind(line, controller, caps)+        InAppCallRegistry.dtmfController = dtmf+        InAppCallRegistry.holdController = hold+        InAppCallRegistry.onCallStarting(+            line = line,+            peerId = "+1555",+            peerName = "Pat",+            isVideo = false,+            incoming = false,+            capabilities = caps,+        )+    }++    // -- presets + predicates ---------------------------------------------------++    @Test+    fun `capability presets expose the right controls`() {+        assertFalse(CallCapabilities.AudioOnly.video)+        assertFalse(CallCapabilities.AudioOnly.dtmf)+        assertTrue(CallCapabilities.AudioOnly.mute)+        assertTrue(CallCapabilities.AudioOnly.speaker)++        assertTrue(CallCapabilities.AudioAndVideo.video)+        assertTrue(CallCapabilities.AudioAndVideo.screenShare)+        assertFalse(CallCapabilities.AudioAndVideo.dtmf)++        assertTrue(CallCapabilities.AudioAndKeypad.dtmf)+        assertFalse(CallCapabilities.AudioAndKeypad.video)+    }++    @Test+    fun `isLiveCall covers ringing connecting and active only`() {+        assertTrue(InAppCallPhase.Incoming.isLiveCall())+        assertTrue(InAppCallPhase.Outgoing.isLiveCall())+        assertTrue(InAppCallPhase.Connecting.isLiveCall())+        assertTrue(InAppCallPhase.Active.isLiveCall())+        assertFalse(InAppCallPhase.Idle.isLiveCall())+        assertFalse(InAppCallPhase.Ended.isLiveCall())+    }++    @Test+    fun `fresh state is idle with no peer`() {+        val state = InAppCallRegistry.state.value+        assertEquals(InAppCallPhase.Idle, state.phase)+        assertNull(state.line)+        assertEquals("", state.peerId)+        assertFalse(state.isRinging)+        assertFalse(state.isOngoing)+    }++    // -- call lifecycle -----------------------------------------------------------++    @Test+    fun `outgoing start seeds peer and video flags`() {+        startOutgoing()+        val state = InAppCallRegistry.state.value+        assertEquals(InAppCallPhase.Outgoing, state.phase)+        assertEquals(CommunicateLine.Sim, state.line)+        assertEquals("+1555", state.peerId)+        assertEquals("Pat", state.peerName)+        assertFalse(state.isVideo)+        assertFalse(state.localVideoEnabled)+        assertFalse(state.speaker)+    }++    @Test+    fun `outgoing video call starts with camera and speaker on`() {+        InAppCallRegistry.bind(CommunicateLine.Signal, controller, CallCapabilities.AudioAndVideo)+        InAppCallRegistry.onCallStarting(+            line = CommunicateLine.Signal,+            peerId = "aci1",+            peerName = "",+            isVideo = true,+            incoming = false,+            capabilities = CallCapabilities.AudioAndVideo,+        )+        val state = InAppCallRegistry.state.value+        assertEquals(InAppCallPhase.Outgoing, state.phase)+        assertEquals("aci1", state.peerName) // blank name falls back to the id+        assertTrue(state.localVideoEnabled)+        assertTrue(state.speaker)+    }++    @Test+    fun `incoming start does not enable camera`() {+        InAppCallRegistry.onCallStarting(+            line = CommunicateLine.Signal,+            peerId = "aci1",+            peerName = "Sam",+            isVideo = true,+            incoming = true,+            capabilities = CallCapabilities.AudioAndVideo,+        )+        val state = InAppCallRegistry.state.value+        assertEquals(InAppCallPhase.Incoming, state.phase)+        assertTrue(state.isRinging)+        assertFalse(state.localVideoEnabled)+        assertFalse(state.speaker)+    }++    @Test+    fun `phase transitions stamp connectedAt once`() {+        startOutgoing()+        InAppCallRegistry.onPhase(InAppCallPhase.Connecting)+        assertTrue(InAppCallRegistry.state.value.isOngoing)+        InAppCallRegistry.onPhase(InAppCallPhase.Active)+        val first = InAppCallRegistry.state.value.connectedAtMs+        assertTrue(first > 0)+        InAppCallRegistry.onPhase(InAppCallPhase.Active)+        assertEquals(first, InAppCallRegistry.state.value.connectedAtMs)+    }++    @Test+    fun `phase while idle is ignored except incoming`() {+        InAppCallRegistry.onPhase(InAppCallPhase.Active)+        assertEquals(InAppCallPhase.Idle, InAppCallRegistry.state.value.phase)+        InAppCallRegistry.onPhase(InAppCallPhase.Incoming)+        assertEquals(InAppCallPhase.Incoming, InAppCallRegistry.state.value.phase)+    }++    @Test+    fun `end then clear resets to a fresh idle`() {+        startOutgoing()+        InAppCallRegistry.onPhase(InAppCallPhase.Active)+        InAppCallRegistry.onEnded("busy")+        assertEquals(InAppCallPhase.Ended, InAppCallRegistry.state.value.phase)+        assertEquals("busy", InAppCallRegistry.state.value.endReason)+        InAppCallRegistry.clearEnded()+        val state = InAppCallRegistry.state.value+        assertEquals(InAppCallPhase.Idle, state.phase)+        assertNull(state.line)+        assertNull(state.endReason)+    }++    @Test+    fun `end while idle is a no-op and clear only acts on ended`() {+        InAppCallRegistry.onEnded("nothing")+        assertEquals(InAppCallPhase.Idle, InAppCallRegistry.state.value.phase)+        startOutgoing()+        InAppCallRegistry.clearEnded()+        assertEquals(InAppCallPhase.Outgoing, InAppCallRegistry.state.value.phase)+    }++    // -- toggles + controller fan-out ----------------------------------------------++    @Test+    fun `mute and speaker toggle through the controller`() {+        startOutgoing()+        InAppCallRegistry.toggleMuted()+        assertTrue(InAppCallRegistry.state.value.muted)+        InAppCallRegistry.toggleSpeaker()+        assertTrue(InAppCallRegistry.state.value.speaker)+        assertEquals(listOf("muted=true", "speaker=true"), actions)+        InAppCallRegistry.toggleMuted()+        assertFalse(InAppCallRegistry.state.value.muted)+    }++    @Test+    fun `answer reject hangup forward with source`() {+        startOutgoing()+        InAppCallRegistry.answer("test")+        InAppCallRegistry.reject("test")+        InAppCallRegistry.hangup("test")+        assertEquals(listOf("answer", "reject", "hangup"), actions)+    }++    @Test+    fun `hold toggles only off idle`() {+        // No call: held stays false and the controller is not poked.+        InAppCallRegistry.toggleHeld()+        assertFalse(InAppCallRegistry.state.value.held)+        assertTrue(actions.isEmpty())++        startOutgoing()+        InAppCallRegistry.toggleHeld()+        assertTrue(InAppCallRegistry.state.value.held)+        InAppCallRegistry.onHeld(false)+        assertFalse(InAppCallRegistry.state.value.held)+        assertEquals(listOf("held=true"), actions)+    }++    @Test+    fun `dtmf forwards to the dtmf controller`() {+        startOutgoing()+        InAppCallRegistry.sendDtmf("5")+        assertEquals(listOf("dtmf=5"), actions)+    }++    @Test+    fun `remote video and screenshare flags track the peer`() {+        startOutgoing()+        InAppCallRegistry.onRemoteVideo(true)+        assertTrue(InAppCallRegistry.state.value.remoteVideoEnabled)+        InAppCallRegistry.onRemoteScreenShare(true)+        assertTrue(InAppCallRegistry.state.value.remoteScreenSharing)+        // Idle guards: with no call these are ignored.+        InAppCallRegistry.onEnded(null)+        InAppCallRegistry.clearEnded()+        InAppCallRegistry.onRemoteVideo(true)+        assertFalse(InAppCallRegistry.state.value.remoteVideoEnabled)+    }++    @Test+    fun `local video implies video and forces speaker`() {+        startOutgoing()+        InAppCallRegistry.onLocalVideo(true)+        val state = InAppCallRegistry.state.value+        assertTrue(state.localVideoEnabled)+        assertTrue(state.isVideo)+    }++    @Test+    fun `enabling video routes hands-free through the line controller`() {+        startOutgoing()+        assertFalse(InAppCallRegistry.state.value.speaker)+        // Video on routes hands-free through the line controller.+        InAppCallRegistry.toggleVideo()+        assertTrue(InAppCallRegistry.state.value.localVideoEnabled)+        assertTrue(InAppCallRegistry.state.value.speaker)+        assertEquals(listOf("speaker=true"), actions.filter { it.startsWith("speaker") })+    }++    @Test+    fun `screenshare without permission is refused`() {+        startOutgoing()+        InAppCallRegistry.setScreenShare(true, null)+        assertFalse(InAppCallRegistry.state.value.screenSharing)+    }++    @Test+    fun `bind updates the line and the given capabilities`() {+        startOutgoing(caps = CallCapabilities.AudioAndKeypad)+        InAppCallRegistry.bind(CommunicateLine.GoogleVoice, controller, CallCapabilities.AudioAndVideo)+        assertTrue(InAppCallRegistry.state.value.capabilities.video)+        assertEquals(CommunicateLine.GoogleVoice, InAppCallRegistry.state.value.line)+        // The default resets to audio-only.+        InAppCallRegistry.bind(CommunicateLine.Signal, controller)+        assertEquals(CallCapabilities.AudioOnly, InAppCallRegistry.state.value.capabilities)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/InAppCallStateSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/InAppCallStateSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/InAppCallStateSlice4Test.ktnew file mode 100644index 0000000000..7593896931--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/InAppCallStateSlice4Test.kt@@ -0,0 +1,72 @@+package com.vayunmathur.communicate.data++import com.vayunmathur.communicate.data.call.CallCapabilities+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallState+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Slice-4 coverage for the call-state data ([InAppCallState]).+ *+ * Pure JVM: pins the defaults, the ringing/ongoing derivations and copy+ * semantics — the shape every call screen renders from.+ */+class InAppCallStateSlice4Test {++    @Test+    fun `defaults describe no call`() {+        val state = InAppCallState()+        assertEquals(InAppCallPhase.Idle, state.phase)+        assertEquals("", state.peerId)+        assertEquals("", state.peerName)+        assertFalse(state.isVideo)+        assertFalse(state.muted)+        assertFalse(state.speaker)+        assertFalse(state.held)+        assertEquals(0L, state.connectedAtMs)+        assertFalse(state.isRinging)+        assertFalse(state.isOngoing)+    }++    @Test+    fun `ringing only while incoming`() {+        for (phase in InAppCallPhase.entries) {+            assertEquals(+                phase == InAppCallPhase.Incoming,+                InAppCallState(phase = phase).isRinging,+                phase.name,+            )+        }+    }++    @Test+    fun `ongoing while active or connecting`() {+        assertTrue(InAppCallState(phase = InAppCallPhase.Active).isOngoing)+        assertTrue(InAppCallState(phase = InAppCallPhase.Connecting).isOngoing)+        assertFalse(InAppCallState(phase = InAppCallPhase.Outgoing).isOngoing)+        assertFalse(InAppCallState(phase = InAppCallPhase.Incoming).isOngoing)+        assertFalse(InAppCallState(phase = InAppCallPhase.Ended).isOngoing)+        assertFalse(InAppCallState(phase = InAppCallPhase.Idle).isOngoing)+    }++    @Test+    fun `copy preserves untouched fields`() {+        val state = InAppCallState(+            phase = InAppCallPhase.Active,+            line = CommunicateLine.Signal,+            peerId = "aci",+            peerName = "Sam",+            isVideo = true,+            capabilities = CallCapabilities.AudioAndVideo,+            connectedAtMs = 123L,+        )+        val muted = state.copy(muted = true)+        assertTrue(muted.muted)+        assertEquals("Sam", muted.peerName)+        assertEquals(123L, muted.connectedAtMs)+        assertEquals(state.copy(), state)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/SimManagerSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/SimManagerSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/SimManagerSlice4Test.ktnew file mode 100644index 0000000000..cfdd754537--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/SimManagerSlice4Test.kt@@ -0,0 +1,104 @@+package com.vayunmathur.communicate.data++import android.Manifest+import android.app.Application+import android.telephony.SubscriptionInfo+import android.telephony.SubscriptionManager+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * Slice-4 coverage for SIM enumeration ([SimManager]).+ *+ * Robolectric (permission grant/deny + subscription shadow): pins the+ * no-permission empty fallback, the single/multi-SIM line choices, the+ * display-name/carrier/fallback label chain, and the subscription lookup —+ * the logic that decides which SIM line a message or call goes out on.+ */+@RunWith(RobolectricTestRunner::class)+class SimManagerSlice4Test {++    private val context: Application+        get() = ApplicationProvider.getApplicationContext()++    private fun grantPhoneState() {+        shadowOf(context).grantPermissions(Manifest.permission.READ_PHONE_STATE)+    }++    private fun denyPhoneState() {+        shadowOf(context).denyPermissions(Manifest.permission.READ_PHONE_STATE)+    }++    private fun subManager(): SubscriptionManager = context.getSystemService(SubscriptionManager::class.java)!!++    private fun setSubs(vararg infos: SubscriptionInfo) {+        shadowOf(subManager()).setActiveSubscriptionInfoList(infos.toList())+    }++    private fun info(subId: Int, slot: Int, display: String?, carrier: String?): SubscriptionInfo =+        org.robolectric.shadows.ShadowSubscriptionManager.SubscriptionInfoBuilder.newBuilder()+            .setId(subId)+            .setSimSlotIndex(slot)+            .apply { display?.let { setDisplayName(it) } }+            .apply { carrier?.let { setCarrierName(it) } }+            .buildSubscriptionInfo()++    @Test+    fun `no permission yields no sims and default line choice`() {+        denyPhoneState()+        assertTrue(SimManager.activeSims(context).isEmpty())+        val choices = SimManager.simLineChoices(context)+        assertEquals(1, choices.size)+        assertEquals(SimManager.defaultSmsSubscriptionId(), choices.single().subscriptionId)+        assertNull(SimManager.labelForSubscription(context, 1))+        assertNull(SimManager.labelForSubscription(context, null))+    }++    @Test+    fun `empty subscription list falls back to the default line`() {+        grantPhoneState()+        setSubs()+        assertTrue(SimManager.activeSims(context).isEmpty())+        assertEquals(1, SimManager.simLineChoices(context).size)+    }++    @Test+    fun `single sim keeps its name`() {+        grantPhoneState()+        setSubs(info(subId = 7, slot = 0, display = "Personal", carrier = "Carrier"))+        val sims = SimManager.activeSims(context)+        assertEquals(listOf(CommunicateSim(7, 0, "Personal")), sims)+        val choices = SimManager.simLineChoices(context)+        assertEquals(1, choices.size)+        assertEquals(LineChoice.Sim(7, "Personal"), choices.single())+        assertEquals("Personal", SimManager.labelForSubscription(context, 7))+    }++    @Test+    fun `blank display falls back to carrier then slot label`() {+        grantPhoneState()+        setSubs(+            info(subId = 1, slot = 0, display = "  ", carrier = "CarrierA"),+            info(subId = 2, slot = 1, display = null, carrier = ""),+        )+        val sims = SimManager.activeSims(context)+        assertEquals("CarrierA", sims[0].displayName)+        assertEquals("SIM 2", sims[1].displayName)+        // Multiple SIMs: one choice each.+        assertEquals(2, SimManager.simLineChoices(context).size)+        assertEquals("CarrierA", SimManager.labelForSubscription(context, 1))+        assertNull(SimManager.labelForSubscription(context, 999))+    }++    @Test+    fun `default sms id never throws`() {+        grantPhoneState()+        SimManager.defaultSmsSubscriptionId()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceAuthSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceAuthSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceAuthSlice4Test.ktnew file mode 100644index 0000000000..956475416f--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceAuthSlice4Test.kt@@ -0,0 +1,49 @@+package com.vayunmathur.communicate.googlevoice++import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceAuth+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice-4 coverage for the remaining Google Voice auth surface ([GoogleVoiceAuth]).+ *+ * Pure JVM: pins the full header set (every header the RPCs require) and the+ * hash construction, so a dropped header is caught without a live session.+ */+class GoogleVoiceAuthSlice4Test {++    @Test+    fun sapisidHash_signsTimestampSapisidAndOrigin() {+        val expected = "1700000000_" + GoogleVoiceAuth.sha1Hex("1700000000 sid9 https://example.com")+        assertEquals(expected, GoogleVoiceAuth.sapisidHash(1700000000L, "sid9", "https://example.com"))+    }++    @Test+    fun authorization_prefixesTheHash() {+        assertEquals(+            "SAPISIDHASH " + GoogleVoiceAuth.sapisidHash(42L, "s"),+            GoogleVoiceAuth.authorization(42L, "s"),+        )+    }++    @Test+    fun headers_coverEveryRequiredField() {+        val headers = GoogleVoiceAuth.headers(+            cookieHeader = "SAPISID=s; A=1",+            sapisid = "s",+            authUser = "3",+            nowSeconds = 100L,+        )+        assertEquals("SAPISID=s; A=1", headers["Cookie"])+        assertEquals("3", headers["X-Goog-AuthUser"])+        assertEquals("application/json+protobuf", headers["Content-Type"])+        assertEquals("https://voice.google.com", headers["Origin"])+        assertEquals("https://voice.google.com/", headers["Referer"])+        assertEquals("XMLHttpRequest", headers["X-Requested-With"])+        assertTrue(headers["User-Agent"]!!.contains("Chrome/"), headers["User-Agent"])+        assertEquals("SAPISIDHASH " + GoogleVoiceAuth.sapisidHash(100L, "s"), headers["Authorization"])+        assertEquals(GoogleVoiceAuth.ORIGIN, "https://voice.google.com")+        assertEquals(GoogleVoiceAuth.CONTENT_TYPE, "application/json+protobuf")+    }+}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceCallStateSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceCallStateSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceCallStateSlice4Test.ktnew file mode 100644index 0000000000..18667f1da2--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceCallStateSlice4Test.kt@@ -0,0 +1,92 @@+package com.vayunmathur.communicate.googlevoice++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.googlevoice.call.CallPhase+import com.vayunmathur.communicate.data.googlevoice.call.CallState+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallBridge+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the Google Voice call state ([CallState]/[CallPhase])+ * and the synchronous [GoogleVoiceCallManager] controls.+ *+ * Robolectric (the manager touches `Log` + app context). Only deterministic,+ * network-free behavior is asserted — mute/speaker flags, no-op guards, and+ * state reset — the async SIP/WebRTC leg needs a live registrar.+ */+@RunWith(RobolectricTestRunner::class)+class GoogleVoiceCallStateSlice4Test {++    @Test+    fun `call state defaults to idle`() {+        val state = CallState()+        assertEquals(CallPhase.Idle, state.phase)+        assertEquals("", state.remoteNumber)+        assertFalse(state.muted)+        assertFalse(state.speaker)+    }++    @Test+    fun `manager starts idle and clears terminal state`() {+        ApplicationProvider.getApplicationContext<android.content.Context>()+        GoogleVoiceCallManager.init(+            ApplicationProvider.getApplicationContext<android.content.Context>(),+        )+        assertEquals(CallPhase.Idle, GoogleVoiceCallManager.state.value.phase)+        // Nothing terminal: clear is a no-op that keeps Idle.+        GoogleVoiceCallManager.clearEnded()+        assertEquals(CallPhase.Idle, GoogleVoiceCallManager.state.value.phase)+    }++    @Test+    fun `mute and speaker update state without audio`() {+        ApplicationProvider.getApplicationContext<android.content.Context>()+        GoogleVoiceCallManager.init(+            ApplicationProvider.getApplicationContext<android.content.Context>(),+        )+        GoogleVoiceCallManager.setMuted(true)+        assertTrue(GoogleVoiceCallManager.state.value.muted)+        GoogleVoiceCallManager.setMuted(false)+        assertFalse(GoogleVoiceCallManager.state.value.muted)+        GoogleVoiceCallManager.setSpeaker(true)+        assertTrue(GoogleVoiceCallManager.state.value.speaker)+        GoogleVoiceCallManager.setSpeaker(false)+        assertFalse(GoogleVoiceCallManager.state.value.speaker)+    }++    @Test+    fun `dtmf without audio is a safe no-op`() {+        ApplicationProvider.getApplicationContext<android.content.Context>()+        GoogleVoiceCallManager.init(+            ApplicationProvider.getApplicationContext<android.content.Context>(),+        )+        GoogleVoiceCallManager.sendDtmf("5")+    }++    @Test+    fun `stop registration resets to idle`() {+        ApplicationProvider.getApplicationContext<android.content.Context>()+        GoogleVoiceCallManager.init(+            ApplicationProvider.getApplicationContext<android.content.Context>(),+        )+        GoogleVoiceCallManager.stopRegistration()+        assertEquals(CallState(), GoogleVoiceCallManager.state.value)+    }++    @Test+    fun `bridge start is idempotent`() {+        val context: android.content.Context = ApplicationProvider.getApplicationContext()+        GoogleVoiceCallManager.init(context)+        GoogleVoiceCallBridge.ensureStarted()+        GoogleVoiceCallBridge.ensureStarted()+        GoogleVoiceCallManager.stopRegistration()+        com.vayunmathur.communicate.data.call.InAppCallRegistry.onEnded("reset")+        com.vayunmathur.communicate.data.call.InAppCallRegistry.clearEnded()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceMediaSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceMediaSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceMediaSlice4Test.ktnew file mode 100644index 0000000000..16d71f6a20--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceMediaSlice4Test.kt@@ -0,0 +1,125 @@+package com.vayunmathur.communicate.googlevoice++import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser+import com.vayunmathur.communicate.data.googlevoice.hasMediaMetadataIn+import com.vayunmathur.communicate.data.googlevoice.isMmsStatusLabel+import com.vayunmathur.communicate.data.googlevoice.looksLikeAttachmentId+import com.vayunmathur.communicate.data.googlevoice.looksLikeMediaUrl+import com.vayunmathur.communicate.data.googlevoice.looksLikeMimeType+import com.vayunmathur.communicate.data.googlevoice.recordId+import com.vayunmathur.communicate.data.googlevoice.transcriptText+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonNull+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonArray+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-4 coverage for the Google Voice media/metadata helpers+ * (`GoogleVoiceMedia.kt`).+ *+ * Pure JVM: pins MMS-label suppression, media-URL detection, attachment-id+ * recognition and transcript extraction — the heuristics that decide whether a+ * message renders text, an image, or a voicemail transcript.+ */+class GoogleVoiceMediaSlice4Test {++    private fun item(vararg slots: Any?): JsonArray = buildJsonArray {+        for (s in slots) when (s) {+            null -> add(JsonNull)+            is String -> add(JsonPrimitive(s))+            is Long -> add(JsonPrimitive(s))+            is Int -> add(JsonPrimitive(s))+        }+    }++    /** 17-slot item with body at 9 and counterparty at 15, like the wire. */+    private fun messageItem(body: String, extra: Map<Int, Any?> = emptyMap()): JsonArray {+        val slots = MutableList<Any?>(17) { null }+        slots[GoogleVoiceParser.ITEM_ID] = "m1"+        slots[GoogleVoiceParser.ITEM_TS] = 1_786_409_649_630L+        slots[GoogleVoiceParser.ITEM_OWN] = "+1000"+        slots[GoogleVoiceParser.ITEM_BODY] = body+        slots[GoogleVoiceParser.ITEM_COUNTERPARTY] = "+1415"+        for ((i, v) in extra) slots[i] = v+        return item(*slots.toTypedArray())+    }++    @Test+    fun isMmsStatusLabel_matchesOnlyTheCarrierLabels() {+        assertTrue("mms sent".isMmsStatusLabel())+        assertTrue("MMS Received".isMmsStatusLabel())+        assertFalse("hello".isMmsStatusLabel())+        assertFalse("mms".isMmsStatusLabel())+        assertFalse("".isMmsStatusLabel())+    }++    @Test+    fun looksLikeMimeType_matchesMediaPrefixes() {+        assertTrue("image/jpeg".looksLikeMimeType())+        assertTrue("Video/MP4".looksLikeMimeType())+        assertTrue("audio/ogg".looksLikeMimeType())+        assertFalse("text/plain".looksLikeMimeType())+        assertFalse("application/json".looksLikeMimeType())+    }++    @Test+    fun looksLikeAttachmentId_matchesDashedNumericSuffix() {+        assertTrue("abc_12-345".looksLikeAttachmentId())+        assertTrue("a.b-1".looksLikeAttachmentId())+        assertFalse("hello".looksLikeAttachmentId())+        assertFalse("+1555".looksLikeAttachmentId())+    }++    @Test+    fun looksLikeMediaUrl_requiresGoogleHostAndMediaHint() {+        assertTrue(looksLikeMediaUrl("https://lh3.google.com/media/abc=s0"))+        assertTrue(looksLikeMediaUrl("https://voice.google.com/media/x.jpg"))+        assertFalse(looksLikeMediaUrl("https://example.com/mms/x"))+        assertFalse(looksLikeMediaUrl("https://example.com/image.jpg"))+        assertFalse(looksLikeMediaUrl("http://lh3.google.com/media/abc=s0"))+        assertFalse(looksLikeMediaUrl("https://lh3.google.com/other"))+    }++    @Test+    fun hasMediaMetadataIn_detectsMimeAndAttachmentIds() {+        assertTrue(hasMediaMetadataIn(buildJsonArray { add(JsonPrimitive("image/png")) }))+        assertTrue(hasMediaMetadataIn(buildJsonArray { add(JsonPrimitive("x-99")) }))+        assertFalse(hasMediaMetadataIn(buildJsonArray { add(JsonPrimitive("hello")) }))+        assertFalse(hasMediaMetadataIn(JsonNull))+    }++    @Test+    fun recordId_readsTheLeadingString() {+        assertEquals("t.1", recordId(buildJsonArray { add(JsonPrimitive("t.1")) }))+        assertNull(recordId(buildJsonArray { add(JsonPrimitive(7)) }))+        assertNull(recordId(buildJsonArray {}))+    }++    @Test+    fun transcriptText_joinsWordsAndIgnoresBlanks() {+        fun block(words: List<String?>): JsonArray = buildJsonArray {+            add(JsonPrimitive(0.9))+            add(buildJsonArray {+                for (w in words) {+                    if (w == null) add(JsonNull)+                    else add(buildJsonArray {+                        add(JsonPrimitive(w)); add(JsonNull); add(JsonNull); add(JsonPrimitive(0.8))+                    })+                }+            })+        }+        val slots = MutableList<Any?>(17) { null }+        slots[GoogleVoiceParser.ITEM_TRANSCRIPT] = "__BLOCK__"+        // Splice the real block in (builders cannot nest raw arrays via Any?).+        val base = messageItem("x").toMutableList()+        base[GoogleVoiceParser.ITEM_TRANSCRIPT] = block(listOf("hello", "", "there"))+        val joined = JsonArray(base)+        assertEquals("hello there", joined.transcriptText())+        assertNull(messageItem("x").transcriptText())+    }+}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserSlice4Test.ktnew file mode 100644index 0000000000..8209303f9c--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserSlice4Test.kt@@ -0,0 +1,282 @@+package com.vayunmathur.communicate.googlevoice++import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser+import com.vayunmathur.communicate.data.googlevoice.GvCallType+import com.vayunmathur.communicate.data.googlevoice.GvFolder+import com.vayunmathur.communicate.data.googlevoice.buildAccountBody+import com.vayunmathur.communicate.data.googlevoice.buildBatchUpdateBody+import com.vayunmathur.communicate.data.googlevoice.buildListBody+import com.vayunmathur.communicate.data.googlevoice.buildSearchBody+import com.vayunmathur.communicate.data.googlevoice.buildSendSmsBody+import com.vayunmathur.communicate.data.googlevoice.quote+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-4 coverage for the Google Voice request builders and response parsing+ * ([GoogleVoiceParser]) beyond the shapes already pinned by [GoogleVoiceParserTest].+ *+ * Pure JVM: every positional wire shape is asserted against hand-built bodies,+ * so a slot shift is caught without a live account.+ */+class GoogleVoiceParserSlice4Test {++    // -- request builders -------------------------------------------------------++    @Test+    fun buildListBody_honoursFolderPageSizeAndWindow() {+        assertEquals("[2,20,15,null,null,[null,1,1,1]]", GoogleVoiceParser.buildListBody(GvFolder.Inbox))+        assertEquals("[3,100,50,null,null,[null,1,1,1]]", GoogleVoiceParser.buildListBody(GvFolder.Calls, 100, 50))+        assertEquals("[4,20,15,null,null,[null,1,1,1]]", GoogleVoiceParser.buildListBody(GvFolder.Voicemail))+        assertEquals("[1,20,15,null,null,[null,1,1,1]]", GoogleVoiceParser.buildListBody(GvFolder.All))+        assertEquals("[5,20,15,null,null,[null,1,1,1]]", GoogleVoiceParser.buildListBody(GvFolder.Spam))+    }++    @Test+    fun buildSearchBody_honoursLimit() {+        assertEquals(+            "[\"query\",200,null,null,null,[null,1,1,1]]",+            GoogleVoiceParser.buildSearchBody("query"),+        )+        assertEquals(+            "[\"query\",10,null,null,null,[null,1,1,1]]",+            GoogleVoiceParser.buildSearchBody("query", 10),+        )+    }++    @Test+    fun buildAccountBody_isNullPlusEmptyObject() {+        assertEquals("[null,{}]", GoogleVoiceParser.buildAccountBody())+    }++    @Test+    fun buildSendSmsBody_appendsBotTokenWhenSupplied() {+        val body = GoogleVoiceParser.buildSendSmsBody("+1555", "hi", threadRemoteId = null, clientTxnId = 7L, botToken = "!tok")+        assertEquals("[null,null,null,null,\"hi\",null,[\"+1555\"],null,[7],null,[\"!tok\"]]", body)+    }++    @Test+    fun buildBatchUpdateBody_coversEveryAction() {+        assertEquals(+            "[[[[\"t.1\",null,null,1],[null,null,null,1],1]]]",+            GoogleVoiceParser.buildBatchUpdateBody("t.1", GoogleVoiceParser.ThreadAction.MarkRead),+        )+        assertEquals(+            "[[[[\"t.1\",null,null,0],[null,null,null,1],1]]]",+            GoogleVoiceParser.buildBatchUpdateBody("t.1", GoogleVoiceParser.ThreadAction.MarkUnread),+        )+        assertEquals(+            "[[[[\"t.1\",null,1],[null,null,1],1]]]",+            GoogleVoiceParser.buildBatchUpdateBody("t.1", GoogleVoiceParser.ThreadAction.Archive),+        )+        assertEquals(+            "[[[[\"t.1\",null,0],[null,null,1],1]]]",+            GoogleVoiceParser.buildBatchUpdateBody("t.1", GoogleVoiceParser.ThreadAction.Unarchive),+        )+    }++    @Test+    fun quote_escapesForEmbedding() {+        assertEquals("\"a\\\"b\"", GoogleVoiceParser.quote("a\"b"))+        assertEquals("\"plain\"", GoogleVoiceParser.quote("plain"))+    }++    @Test+    fun extractBotToken_findsTheBangToken() {+        val body = "[null,null,null,null,\"hi\",null,[\"+1555\"],null,[7],null,[\"!abc123\"]]"+        assertEquals("!abc123", GoogleVoiceParser.extractBotToken(body))+        assertNull(GoogleVoiceParser.extractBotToken("[null,null,[\"no-bang\"]]"))+        assertNull(GoogleVoiceParser.extractBotToken("not json"))+        assertNull(GoogleVoiceParser.extractBotToken(""))+    }++    // -- response parsing ---------------------------------------------------------++    @Test+    fun parseAccount_returnsNullOnGarbageAndFirstPhoneOtherwise() {+        assertNull(GoogleVoiceParser.parseAccount("not json").phoneNumber)+        assertNull(GoogleVoiceParser.parseAccount("").phoneNumber)+        assertNull(GoogleVoiceParser.parseAccount("[null,{}]").phoneNumber)+        assertEquals(+            "+15551234567",+            GoogleVoiceParser.parseAccount("[\"x\",\"+15551234567\",\"y\"]").phoneNumber,+        )+    }++    @Test+    fun parseThreads_returnsEmptyOnGarbageAndDedupes() {+        assertTrue(GoogleVoiceParser.parseThreads("nope").isEmpty())+        assertTrue(GoogleVoiceParser.parseThreads("").isEmpty())+        val one = "[[[\"t.+1415\",1,[[\"h1\",1786409649630,\"+1000\",[\"+1415\"],10,1,null,null,null," ++            "\"hi\",null,null,5,1,null,\"+1415\",0]],null,[[\"+1415\"]]]]]"+        assertEquals(1, GoogleVoiceParser.parseThreads(one).size)+        // Same record twice: distinct by id.+        val doubled = one.dropLast(1) + "," + one.substring(1)+        assertEquals(1, GoogleVoiceParser.parseThreads(doubled).size)+    }++    @Test+    fun parseThreads_sortsMessagesOldestFirstAndSnippetsNewest() {+        val body = "[[[\"t.+1415\",1,[" ++            "[\"n\",1786409649631,\"+1000\",[\"+1415\"],10,1,null,null,null,\"second\",null,null,5,1,null,\"+1415\",0]," ++            "[\"o\",1786409649630,\"+1000\",[\"+1415\"],11,1,null,null,null,\"first\",null,null,5,1,null,\"+1415\",0]" ++            "],null,[[\"+1415\"]]]]]"+        val thread = GoogleVoiceParser.parseThreads(body).single()+        assertEquals(listOf("first", "second"), thread.messages.map { it.text })+        assertEquals("second", thread.snippet)+        assertTrue(thread.messages[0].outgoing) // type 11+        assertFalse(thread.messages[1].outgoing) // type 10+        assertEquals(1786409649631L, thread.timestampMillis)+    }++    @Test+    fun parseThreads_skipsMessagesWithoutTimestamps() {+        val body = "[[[\"t.+1415\",1,[" ++            "[\"n\",null,\"+1000\",[\"+1415\"],10,1,null,null,null,\"no-ts\",null,null,5,1,null,\"+1415\",0]" ++            "],null,[[\"+1415\"]]]]]"+        val thread = GoogleVoiceParser.parseThreads(body).single()+        assertTrue(thread.messages.isEmpty())+        assertEquals("", thread.snippet)+    }++    @Test+    fun parseThreadMessages_missesOnUnknownThread() {+        val body = "[[[\"t.+1415\",1,[[\"h1\",1786409649630,\"+1000\",[\"+1415\"],10,1,null,null,null," ++            "\"hi\",null,null,5,1,null,\"+1415\",0]],null,[[\"+1415\"]]]]]"+        assertEquals(1, GoogleVoiceParser.parseThreadMessages(body, "t.+1415").size)+        assertTrue(GoogleVoiceParser.parseThreadMessages(body, "t.+9999").isEmpty())+        assertTrue(GoogleVoiceParser.parseThreadMessages("garbage", "t.+1415").isEmpty())+    }++    @Test+    fun parseCalls_classifiesDirectionAndMisses() {+        // Outgoing: own number equals the counterparty.+        val out = "[[[\"c.out\",1,[[\"h\",1786409649630,\"+1415\",[\"+1415\"],14,1,null,null,60," ++            "null,null,null,5,1,null,\"+1415\",0]],null]]]"+        val outgoing = GoogleVoiceParser.parseCalls(out).single()+        assertEquals(GvCallType.Outgoing, outgoing.type)+        assertEquals(60L, outgoing.durationSeconds)+        assertEquals("+1415", outgoing.phoneNumber)++        // Incoming with duration; missed when zero.+        val inc = "[[[\"c.inc\",1,[[\"h\",1786409649630,\"+1000\",[\"+1415\"],14,1,null,null,30," ++            "null,null,null,5,1,null,\"+1415\",0]],null]]]"+        assertEquals(GvCallType.Incoming, GoogleVoiceParser.parseCalls(inc).single().type)+        val missed = "[[[\"c.m\",1,[[\"h\",1786409649630,\"+1000\",[\"+1415\"],14,1,null,null,0," ++            "null,null,null,5,1,null,\"+1415\",0]],null]]]"+        assertEquals(GvCallType.Missed, GoogleVoiceParser.parseCalls(missed).single().type)++        assertTrue(GoogleVoiceParser.parseCalls("garbage").isEmpty())+        // Record with no items has no counterparty and is dropped.+        assertTrue(GoogleVoiceParser.parseCalls("[[[\"c.x\",1,[],null]]]").isEmpty())+    }++    @Test+    fun parseVoicemails_filtersNonVoicemailAndReadsTranscript() {+        // type slot 4 = 2 marks voicemail; transcript at slot 6; audio URL at 11; read flag at 13.+        fun item(type: Long, read: Long, words: String?): String {+            val transcript = words?.let {+                "[0.9,[[\"$it\",null,null,0.8]]]"+            } ?: "null"+            // slots: 0 id, 1 ts, 2 own, 3 participants, 4 type, 5 ?, 6 transcript, 7-10 ?,+            // 11 audio, 12 ?, 13 read, 14 ?, 15 counterparty+            return "[\"v1\",1786409649630,\"+1000\",[\"+1415\"],$type,null,$transcript,null,null,null,null," ++                "\"https://voice.google.com/media/a\",null,$read,null,\"+1415\"]"+        }+        val body = "[[[\"c.vm\",1,[${item(2, 1, "hello there")}],null]]]"+        val vm = GoogleVoiceParser.parseVoicemails(body).single()+        assertEquals("c.vm", vm.id)+        assertEquals("+1415", vm.phoneNumber)+        assertEquals("hello there", vm.transcript)+        assertEquals("https://voice.google.com/media/a", vm.audioUrl)+        assertTrue(vm.read)++        // A regular call record (type 14) is not a voicemail.+        val callBody = "[[[\"c.vm\",1,[${item(14, 1, "hello there")}],null]]]"+        assertTrue(GoogleVoiceParser.parseVoicemails(callBody).isEmpty())+        // Unread flag (8) reads as unread; missing transcript is null.+        val unread = "[[[\"c.vm\",1,[${item(2, 8, null)}],null]]]"+        val vmUnread = GoogleVoiceParser.parseVoicemails(unread).single()+        assertFalse(vmUnread.read)+        assertNull(vmUnread.transcript)++        assertTrue(GoogleVoiceParser.parseVoicemails("garbage").isEmpty())+    }++    @Test+    fun parseSipRegisterInfo_returnsPhoneAndOpaqueCreds() {+        val info = GoogleVoiceParser.parseSipRegisterInfo("garbage")+        assertNull(info.phoneNumber)+        assertTrue(info.credentials.isEmpty())++        val body = "[\"+15551234567\",\"short\",\"${"a".repeat(40)}\",\"${"b".repeat(24)}\"]"+        val parsed = GoogleVoiceParser.parseSipRegisterInfo(body)+        assertEquals("+15551234567", parsed.phoneNumber)+        assertEquals(listOf("a".repeat(40), "b".repeat(24)), parsed.credentials)+    }++    @Test+    fun parseCalls_fallsBackAcrossCounterpartySlots() {+        // Item participants: ["+1415"].+        fun item(own: String, parts: String, id: String = "\"h\"") =+            "[$id,1786409649630,\"$own\",[$parts],14,1,null,null,30,null,null,null,5,1,null,\"+1415\",0]"+        // Newest-item participants win.+        val direct = "[[[\"c.d\",1,[${item("+1000", "\"+1415\"")}],null]]]"+        assertEquals("+1415", GoogleVoiceParser.parseCalls(direct).single().phoneNumber)+        // Blank item participants: record slot 4 holds the participant array.+        val viaA = "[[[\"c.a\",1,[${item("+1000", "")}],null,[[\"+1425\"]]]]]"+        assertEquals("+1425", GoogleVoiceParser.parseCalls(viaA).single().phoneNumber)+        // Slot 4 not an array: record slot 7, participant 0.+        val viaB = "[[[\"c.b\",1,[${item("+1000", "")}],null,\"x\",null,null,[\"+1435\"]]]]"+        assertEquals("+1435", GoogleVoiceParser.parseCalls(viaB).single().phoneNumber)+        // No slots at all: opaque c. id is not a phone, so the record drops.+        val opaque = "[[[\"c.zzz\",1,[${item("+1000", "")}],null]]]"+        assertTrue(GoogleVoiceParser.parseCalls(opaque).isEmpty())+        // Digit-only t. id IS a phone and becomes the counterparty.+        val digits = "[[[\"t.4155550111\",1,[${item("+1000", "")}],null]]]"+        assertEquals("4155550111", GoogleVoiceParser.parseThreads(digits).single().phoneNumber)+    }++    @Test+    fun gvModels_holdTheirFields() {+        val msg = com.vayunmathur.communicate.data.googlevoice.GvMessage(+            id = "m1",+            threadId = "t.1",+            phoneNumber = "+1415",+            text = "hi",+            timestampMillis = 42L,+            outgoing = false,+            read = true,+            mediaUrls = listOf("https://x/y.jpg"),+        )+        assertEquals("m1", msg.id)+        assertEquals("t.1", msg.threadId)+        assertTrue(msg.read)+        assertTrue(msg.hasMedia)+        val plain = msg.copy(mediaUrls = emptyList())+        assertTrue(plain.mediaUrls.isEmpty())+        assertEquals(msg, msg.copy())+        val thread = com.vayunmathur.communicate.data.googlevoice.GvThread(+            id = "t.1",+            phoneNumber = "+1415",+            displayName = "Alice",+            snippet = "hi",+            timestampMillis = 42L,+            unreadCount = 2,+            messages = listOf(msg),+        )+        assertEquals("Alice", thread.displayName)+        assertEquals(2, thread.unreadCount)+        assertEquals(thread, thread.copy())+        val call = GoogleVoiceParser.parseCalls(+            "[[[\"c.g\",1,[[\"h\",1786409649630,\"+1000\",[\"+1415\"],14,1,null,null,30," ++                "null,null,null,5,1,null,\"+1415\",0]],null]]]",+        ).single()+        assertEquals("c.g", call.id)+        assertNull(call.displayName)+        assertEquals(1786409649630L, call.timestampMillis)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceSessionSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceSessionSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceSessionSlice4Test.ktnew file mode 100644index 0000000000..b32edeb80e--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceSessionSlice4Test.kt@@ -0,0 +1,133 @@+package com.vayunmathur.communicate.googlevoice++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the Google Voice session store ([GoogleVoiceSession]).+ *+ * Robolectric with a real DataStore: persists, reads back, and clears the web+ * session material, so a lost-cookie / lost-key regression is caught without a+ * live sign-in.+ */+@RunWith(RobolectricTestRunner::class)+class GoogleVoiceSessionSlice4Test {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    // -- pure cookie parsing ------------------------------------------------------++    @Test+    fun extractSapisid_prefersPlainSapisidThenSecureVariants() {+        assertEquals(+            "plain1",+            GoogleVoiceSession.extractSapisid("OTHER=1; SAPISID=plain1; X=2"),+        )+        assertEquals(+            "sec3",+            GoogleVoiceSession.extractSapisid("OTHER=1; __Secure-3PAPISID=sec3"),+        )+        assertEquals(+            "sec1",+            GoogleVoiceSession.extractSapisid("__Secure-1PAPISID=sec1"),+        )+        assertNull(GoogleVoiceSession.extractSapisid("OTHER=1; X=2"))+        assertNull(GoogleVoiceSession.extractSapisid(""))+        assertNull(GoogleVoiceSession.extractSapisid("SAPISID=; X=1"))+    }++    // -- persisted session -----------------------------------------------------------++    @Test+    fun freshSession_isSignedOutWithDefaults() = runTest {+        val session = GoogleVoiceSession.get(context)+        session.signOut()+        assertFalse(session.isSignedIn())+        assertNull(session.cookieHeader())+        assertNull(session.sapisid())+        assertNull(session.apiKey())+        assertEquals("0", session.authUser())+        assertNull(session.phoneNumber())+        assertEquals(0L, session.lastSeenMessageTimestampMillis())+        assertFalse(session.hasUsableCredentials())+        assertFalse(session.signedInFlow.first())+    }++    @Test+    fun save_persistsCredentialsAndMarksSignedIn() = runTest {+        val session = GoogleVoiceSession.get(context)+        session.signOut()+        session.save(+            cookieHeader = "SAPISID=sid9; OTHER=1",+            apiKey = "key1",+            authUser = "2",+        )+        assertTrue(session.isSignedIn())+        assertEquals("SAPISID=sid9; OTHER=1", session.cookieHeader())+        assertEquals("sid9", session.sapisid())+        assertEquals("key1", session.apiKey())+        assertEquals("2", session.authUser())+        assertTrue(session.hasUsableCredentials())+        assertTrue(session.signedInFlow.first())+    }++    @Test+    fun save_acceptsAnExplicitSapisid() = runTest {+        val session = GoogleVoiceSession.get(context)+        session.signOut()+        session.save(cookieHeader = "OTHER=1", apiKey = "key1", authUser = "0", sapisid = "given")+        assertEquals("given", session.sapisid())+        assertTrue(session.hasUsableCredentials())+    }++    @Test+    fun updateCookies_refreshesCookieAndSapisid() = runTest {+        val session = GoogleVoiceSession.get(context)+        session.signOut()+        session.save(cookieHeader = "SAPISID=old; OTHER=1", apiKey = "key1", authUser = "0")+        session.updateCookies("SAPISID=new; OTHER=2")+        assertEquals("SAPISID=new; OTHER=2", session.cookieHeader())+        assertEquals("new", session.sapisid())+    }++    @Test+    fun lastSeenWatermark_roundTrips() = runTest {+        val session = GoogleVoiceSession.get(context)+        session.signOut()+        session.setLastSeenMessageTimestampMillis(1_700_000_000_000L)+        assertEquals(1_700_000_000_000L, session.lastSeenMessageTimestampMillis())+    }++    @Test+    fun phoneNumber_roundTripsThroughFlow() = runTest {+        val session = GoogleVoiceSession.get(context)+        session.signOut()+        session.setPhoneNumber("+1555")+        assertEquals("+1555", session.phoneNumber())+        assertEquals("+1555", session.phoneNumberFlow.first())+    }++    @Test+    fun signOut_clearsEverything() = runTest {+        val session = GoogleVoiceSession.get(context)+        session.save(cookieHeader = "SAPISID=s; O=1", apiKey = "k", authUser = "1")+        session.setPhoneNumber("+1555")+        session.setLastSeenMessageTimestampMillis(9L)+        session.signOut()+        assertFalse(session.isSignedIn())+        assertFalse(session.hasUsableCredentials())+        assertNull(session.cookieHeader())+        assertNull(session.phoneNumber())+        assertEquals(0L, session.lastSeenMessageTimestampMillis())+    }+}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/SipHelpersSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/SipHelpersSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/SipHelpersSlice4Test.ktnew file mode 100644index 0000000000..a1513a54cf--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/SipHelpersSlice4Test.kt@@ -0,0 +1,181 @@+package com.vayunmathur.communicate.googlevoice++import com.vayunmathur.communicate.data.googlevoice.GvSipRegisterInfo+import com.vayunmathur.communicate.data.googlevoice.call.SipClient+import com.vayunmathur.communicate.data.googlevoice.call.digestAuth+import com.vayunmathur.communicate.data.googlevoice.call.extractContact+import com.vayunmathur.communicate.data.googlevoice.call.extractParam+import com.vayunmathur.communicate.data.googlevoice.call.extractRecordRoutes+import com.vayunmathur.communicate.data.googlevoice.call.extractTag+import com.vayunmathur.communicate.data.googlevoice.call.extractUserFromHeader+import com.vayunmathur.communicate.data.googlevoice.call.md5+import com.vayunmathur.communicate.data.googlevoice.call.parseHeaders+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-4 coverage for the SIP plumbing ([SipClient] extensions + digest auth).+ *+ * Pure JVM: no socket is ever opened — the client is constructed with a stub+ * listener and only its message builders/parsers are exercised, so registrar+ * framing regressions are caught without a live WebSocket.+ */+class SipHelpersSlice4Test {++    private val listener = object : SipClient.Listener {+        override fun onRegistered() = Unit+        override fun onProvisional(code: Int) = Unit+        override fun onAnswered(remoteSdp: String) = Unit+        override fun onEarlyMedia(remoteSdp: String) = Unit+        override fun onEnded() = Unit+        override fun onFailed(reason: String) = Unit+        override fun onIncomingInvite(remoteSdp: String, from: String) = Unit+    }++    private fun client(+        creds: List<String> = listOf("alice", "secret"),+        gvNumber: String = "+1555",+    ) = SipClient(+        GvSipRegisterInfo(phoneNumber = gvNumber, credentials = creds),+        gvNumber,+        CoroutineScope(SupervisorJob() + Dispatchers.Unconfined),+        listener,+    )++    // -- identity derivation ------------------------------------------------++    @Test+    fun `credentials map to username password and url-encoded aor`() {+        val c = client(listOf("alice=x", "secret"))+        assertEquals("alice=x", c.authUsername)+        assertEquals("secret", c.authPassword)+        assertEquals("alice%3Dx", c.aorUser)+    }++    @Test+    fun `missing credentials fall back to the gv number and empty password`() {+        val c = client(creds = emptyList(), gvNumber = "+1555")+        assertEquals("+1555", c.authUsername)+        assertEquals("", c.authPassword)+        assertEquals("+1555", c.aorUser)+    }++    // -- digest auth ----------------------------------------------------------++    @Test+    fun `md5 matches the known vector`() {+        assertEquals("900150983cd24fb0d6963f7d28e17f72", client().md5("abc"))+    }++    @Test+    fun `digestAuth builds the rfc2069 response`() {+        val c = client(listOf("alice", "secret"))+        // ha1=md5("alice:example.com:secret"), ha2=md5("REGISTER:sip:example.com"),+        // response=md5("$ha1:n123:$ha2") — verified against an independent md5.+        assertEquals(+            "Digest algorithm=MD5, username=\"alice\", realm=\"example.com\", " ++                "nonce=\"n123\", uri=\"sip:example.com\", " ++                "response=\"9b40ed3e8851a750677d0c45eae3d029\"",+            c.digestAuth("REGISTER", "sip:example.com", "n123", "example.com"),+        )+    }++    @Test+    fun `digestAuth binds the method so invite and register differ`() {+        val c = client(listOf("alice", "secret"))+        val register = c.digestAuth("REGISTER", "sip:example.com", "n123", "example.com")+        val invite = c.digestAuth("INVITE", "sip:example.com", "n123", "example.com")+        assertTrue(register != invite)+    }++    // -- header parsing -------------------------------------------------------++    private val response200 = "SIP/2.0 200 OK\r\n" ++        "Via: SIP/2.0/WSS df12.invalid;branch=z9hG4bK1\r\n" ++        "Via: SIP/2.0/WSS df12.invalid;branch=z9hG4bK2\r\n" ++        "From: <sip:[email protected]>;tag=from1\r\n" ++        "To: <sip:[email protected]>;tag=to9\r\n" ++        "Call-ID: abc-123\r\n" ++        "CSeq: 2 INVITE\r\n" ++        "Contact: <sip:[email protected];transport=wss>\r\n" ++        "Record-Route: <sip:r1.example.com;lr>\r\n" ++        "Record-Route: <sip:r2.example.com;lr>\r\n" ++        "Content-Length: 0\r\n" ++        "\r\n"++    @Test+    fun `parseHeaders lowercases names and stops at the body gap`() {+        val headers = client().parseHeaders(response200 + "BODY-SHOULD-NOT-PARSE: x")+        assertEquals("2 INVITE", headers["cseq"])+        assertEquals("<sip:[email protected]>;tag=from1", headers["from"])+        assertEquals("<sip:[email protected]>;tag=to9", headers["to"])+        assertEquals("abc-123", headers["call-id"])+        assertEquals("0", headers["content-length"])+        assertNull(headers["body-should-not-parse"])+    }++    @Test+    fun `parseHeaders keeps the first Via and ignores malformed lines`() {+        val headers = client().parseHeaders("SIP/2.0 200 OK\r\nNoColonHere\r\nVia: a\r\n\r\n")+        assertEquals("a", headers["via"])+    }++    @Test+    fun `extractContact prefers the bracketed uri`() {+        assertEquals(+            "sip:[email protected];transport=wss",+            client().extractContact(response200),+        )+    }++    @Test+    fun `extractContact falls back to the bare value and null when absent`() {+        assertEquals(+            "sip:[email protected]",+            client().extractContact("SIP/2.0 200 OK\r\nContact: sip:[email protected]\r\n\r\n"),+        )+        assertNull(client().extractContact("SIP/2.0 200 OK\r\nContent-Length: 0\r\n\r\n"))+    }++    @Test+    fun `extractRecordRoutes preserves order for later reversal`() {+        assertEquals(+            listOf("<sip:r1.example.com;lr>", "<sip:r2.example.com;lr>"),+            client().extractRecordRoutes(response200),+        )+        assertEquals(+            emptyList(),+            client().extractRecordRoutes("SIP/2.0 200 OK\r\nContent-Length: 0\r\n\r\n"),+        )+    }++    @Test+    fun `extractTag pulls the dialog tag`() {+        assertEquals("to9", client().extractTag("<sip:[email protected]>;tag=to9"))+        assertNull(client().extractTag("<sip:[email protected]>"))+    }++    @Test+    fun `extractParam reads quoted and bare challenge params`() {+        val challenge = "Digest realm=\"example.com\", nonce=\"n123\", algorithm=MD5, stale=false"+        assertEquals("example.com", client().extractParam(challenge, "realm"))+        assertEquals("n123", client().extractParam(challenge, "nonce"))+        assertEquals("MD5", client().extractParam(challenge, "algorithm"))+        assertEquals("false", client().extractParam(challenge, "stale"))+        assertNull(client().extractParam(challenge, "qop"))+    }++    @Test+    fun `extractUserFromHeader pulls the caller number`() {+        assertEquals(+            "+1415",+            client().extractUserFromHeader("\"Bob\" <sip:[email protected]>;tag=x"),+        )+        assertNull(client().extractUserFromHeader("no-sip-here"))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/SipMessagesSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/SipMessagesSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/SipMessagesSlice4Test.ktnew file mode 100644index 0000000000..b76dadcbf6--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/SipMessagesSlice4Test.kt@@ -0,0 +1,216 @@+package com.vayunmathur.communicate.googlevoice++import com.vayunmathur.communicate.data.googlevoice.GvSipRegisterInfo+import com.vayunmathur.communicate.data.googlevoice.call.InboundInvite+import com.vayunmathur.communicate.data.googlevoice.call.SipClient+import com.vayunmathur.communicate.data.googlevoice.call.buildByeOk+import com.vayunmathur.communicate.data.googlevoice.call.buildCancelOk+import com.vayunmathur.communicate.data.googlevoice.call.buildInboundResponse+import com.vayunmathur.communicate.data.googlevoice.call.buildRequest+import com.vayunmathur.communicate.data.googlevoice.call.fromUri+import com.vayunmathur.communicate.data.googlevoice.call.headerLines+import com.vayunmathur.communicate.data.googlevoice.call.parseHeaders+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice-4 coverage for the SIP message builders ([SipClient] extensions).+ *+ * Pure JVM: asserts the exact framing (request line, dialog headers, CSeq+ * accounting, content length) so a malformed REGISTER/INVITE/BYE is caught+ * without a live registrar.+ */+class SipMessagesSlice4Test {++    private val listener = object : SipClient.Listener {+        override fun onRegistered() = Unit+        override fun onProvisional(code: Int) = Unit+        override fun onAnswered(remoteSdp: String) = Unit+        override fun onEarlyMedia(remoteSdp: String) = Unit+        override fun onEnded() = Unit+        override fun onFailed(reason: String) = Unit+        override fun onIncomingInvite(remoteSdp: String, from: String) = Unit+    }++    private fun client() = SipClient(+        GvSipRegisterInfo(phoneNumber = "+1555", credentials = listOf("alice", "secret")),+        "+1555",+        CoroutineScope(SupervisorJob() + Dispatchers.Unconfined),+        listener,+    )++    // -- outbound requests ----------------------------------------------------++    @Test+    fun `buildRequest frames a register with incrementing cseq`() {+        val c = client()+        val first = c.buildRequest("REGISTER", "sip:example.com", "<sip:[email protected]>")+        val second = c.buildRequest("REGISTER", "sip:example.com", "<sip:[email protected]>")+        assertTrue(first.startsWith("REGISTER sip:example.com SIP/2.0\r\n"), first)+        assertTrue(first.contains("CSeq: 2 REGISTER\r\n"), first)+        assertTrue(second.contains("CSeq: 3 REGISTER\r\n"), second)+        // Fixed framing present on both.+        for (msg in listOf(first, second)) {+            assertTrue(msg.contains("Max-Forwards: 70\r\n"))+            assertTrue(msg.contains("From: <sip:alice@${SipClient.SIP_DOMAIN}>;tag="))+            assertTrue(msg.contains("To: <sip:[email protected]>\r\n"))+            assertTrue(msg.contains("Call-ID: "))+            assertTrue(msg.contains("Allow: INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,PRACK\r\n"))+            assertTrue(msg.contains("User-Agent: Communicate GoogleVoice\r\n"))+            assertTrue(msg.endsWith("Content-Length: 0\r\n\r\n"), msg)+        }+    }++    @Test+    fun `buildRequest carries body content-type and exact byte length`() {+        val c = client()+        val sdp = "v=0\r\no=alice 1 1 IN IP4 10.0.0.1\r\n"+        val msg = c.buildRequest(+            method = "INVITE",+            requestUri = "sip:[email protected]",+            to = "<sip:[email protected]>",+            body = sdp,+            contentType = "application/sdp",+        )+        assertTrue(msg.startsWith("INVITE sip:[email protected] SIP/2.0\r\n"))+        assertTrue(msg.contains("Content-Type: application/sdp\r\n"))+        assertTrue(msg.contains("Content-Length: ${sdp.toByteArray().size}\r\n\r\n$sdp"), msg)+    }++    @Test+    fun `buildRequest honours cseqOverride and extra headers`() {+        val c = client()+        val msg = c.buildRequest(+            method = "ACK",+            requestUri = "sip:[email protected]",+            to = "<sip:[email protected]>;tag=t1",+            extraHeaders = listOf("Route: <sip:r1>", "Route: <sip:r2>"),+            cseqOverride = 7,+        )+        assertTrue(msg.contains("CSeq: 7 ACK\r\n"), msg)+        assertTrue(msg.contains("Route: <sip:r1>\r\nRoute: <sip:r2>\r\n"), msg)+    }++    @Test+    fun `buildRequest without increment reuses the cseq`() {+        val c = client()+        val before = c.buildRequest("OPTIONS", "sip:example.com", "x", incrementCseq = false)+        val after = c.buildRequest("OPTIONS", "sip:example.com", "x", incrementCseq = false)+        assertEquals(+            before.substringAfter("CSeq: ").substringBefore("\r\n"),+            after.substringAfter("CSeq: ").substringBefore("\r\n"),+        )+    }++    @Test+    fun `fromUri builds the aor`() {+        assertEquals("<sip:[email protected]>".replace("example.com", SipClient.SIP_DOMAIN), client().fromUri())+    }++    @Test+    fun `headerLines picks one header case-insensitively before the body`() {+        val c = client()+        val msg = "INVITE sip:x SIP/2.0\r\nVia: a\r\nvIa: b\r\nFrom: f\r\n\r\nVia: body\r\n"+        assertEquals(listOf("Via: a", "vIa: b"), c.headerLines(msg, "via"))+        assertEquals(listOf("From: f"), c.headerLines(msg, "FROM"))+        assertEquals(emptyList(), c.headerLines(msg, "Contact"))+    }++    // -- inbound responses ------------------------------------------------------++    private fun invite(): InboundInvite = InboundInvite(+        viaLines = listOf("Via: SIP/2.0/WSS r.example.com;branch=z9hG4bK1"),+        recordRouteLines = listOf("Record-Route: <sip:r1;lr>"),+        from = "\"Bob\" <sip:[email protected]>;tag=f1",+        to = "<sip:[email protected]>",+        callId = "call-1",+        cseq = "1 INVITE",+        responseToTag = "resp1",+    )++    @Test+    fun `provisional responses carry no tag final ones do`() {+        val c = client()+        val trying = c.buildInboundResponse(invite(), 100, "Trying")+        assertTrue(trying.startsWith("SIP/2.0 100 Trying\r\n"), trying)+        assertTrue(trying.contains("To: <sip:[email protected]>\r\n"), trying)++        val ringing = c.buildInboundResponse(invite(), 180, "Ringing")+        assertTrue(ringing.contains("To: <sip:[email protected]>;tag=resp1\r\n"), ringing)++        val ok = c.buildInboundResponse(invite(), 200, "OK", body = "v=0", contentType = "application/sdp")+        assertTrue(ok.contains("To: <sip:[email protected]>;tag=resp1\r\n"), ok)+        assertTrue(ok.contains("Contact: <sip:"), ok)+        assertTrue(ok.contains("Content-Type: application/sdp\r\n"), ok)+        assertTrue(ok.endsWith("\r\n\r\nv=0"), ok)+    }++    @Test+    fun `inbound response echoes dialog state`() {+        val c = client()+        val msg = c.buildInboundResponse(invite(), 200, "OK")+        assertTrue(msg.contains("Via: SIP/2.0/WSS r.example.com;branch=z9hG4bK1\r\n"), msg)+        assertTrue(msg.contains("From: \"Bob\" <sip:[email protected]>;tag=f1\r\n"), msg)+        assertTrue(msg.contains("Call-ID: call-1\r\n"), msg)+        assertTrue(msg.contains("CSeq: 1 INVITE\r\n"), msg)+        assertTrue(msg.contains("Record-Route: <sip:r1;lr>\r\n"), msg)+    }++    @Test+    fun `inbound invite to-tag logic`() {+        // Already-tagged To passes through untouched for every code.+        val tagged = invite().copy(to = "<sip:[email protected]>;tag=orig")+        assertEquals("", tagged.toTagForResponse(100))+        assertEquals("", tagged.toTagForResponse(200))+        // Untagged: no tag at/below 100, tag above.+        assertEquals("", invite().toTagForResponse(100))+        assertEquals(";tag=resp1", invite().toTagForResponse(180))+        assertEquals(";tag=resp1", invite().toTagForResponse(200))+    }++    @Test+    fun `inbound invite parses from raw message`() {+        val c = client()+        val raw = "INVITE sip:[email protected] SIP/2.0\r\n" ++            "Via: SIP/2.0/WSS r1;branch=1\r\n" ++            "Via: SIP/2.0/WSS r2;branch=2\r\n" ++            "From: \"Bob\" <sip:[email protected]>;tag=f1\r\n" ++            "To: <sip:[email protected]>\r\n" ++            "Call-ID: call-9\r\n" ++            "CSeq: 4 INVITE\r\n" ++            "Record-Route: <sip:rr;lr>\r\n" ++            "Contact: <sip:[email protected]>\r\n" ++            "Content-Length: 3\r\n" ++            "\r\n" ++            "v=0"+        val parsed = InboundInvite.from(raw, c.parseHeaders(raw))+        assertEquals(2, parsed.viaLines.size)+        assertEquals(1, parsed.recordRouteLines.size)+        assertEquals("call-9", parsed.callId)+        assertEquals("4 INVITE", parsed.cseq)+    }++    @Test+    fun `cancel and bye acks mirror the request headers`() {+        val c = client()+        val raw = "CANCEL sip:[email protected] SIP/2.0\r\n" ++            "Via: SIP/2.0/WSS r1;branch=1\r\n" ++            "From: f\r\nTo: t\r\nCall-ID: c1\r\nCSeq: 4 CANCEL\r\n\r\n"+        val headers = mapOf(+            "from" to "f", "to" to "t", "call-id" to "c1", "cseq" to "4 CANCEL",+        )+        for (ack in listOf(c.buildCancelOk(raw, headers), c.buildByeOk(raw, headers))) {+            assertTrue(ack.startsWith("SIP/2.0 200 OK\r\n"), ack)+            assertTrue(ack.contains("Via: SIP/2.0/WSS r1;branch=1\r\n"), ack)+            assertTrue(ack.contains("From: f\r\n"), ack)+            assertTrue(ack.contains("To: t\r\n"), ack)+            assertTrue(ack.contains("Call-ID: c1\r\n"), ack)+            assertTrue(ack.contains("CSeq: 4 CANCEL\r\n"), ack)+            assertTrue(ack.endsWith("Content-Length: 0\r\n\r\n"), ack)+        }+    }+}
communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.ktnew file mode 100644index 0000000000..dc809c75f3--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/notifications/ConversationSpaceSlice4Test.kt@@ -0,0 +1,139 @@+package com.vayunmathur.communicate.notifications++import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.CommunicateLine+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the Conversation Space wiring ([ConversationSpace]).+ *+ * Robolectric (resource + framework access). The pure id/extra mapping is+ * asserted exactly — it is what keeps per-conversation notifications from+ * clobbering each other — and posting paths are exercised through the real+ * NotificationManager shadow.+ */+@RunWith(RobolectricTestRunner::class)+class ConversationSpaceSlice4Test {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    private fun target(+        line: CommunicateLine = CommunicateLine.Sim,+        address: String = "+1555",+        remoteId: String? = null,+        threadId: Long = 42L,+        name: String = "Pat",+    ) = ConversationTarget(+        line = line,+        address = address,+        remoteId = remoteId,+        threadId = threadId,+        personName = name,+    )++    @Test+    fun `shortcutId prefers remoteId then threadId then address`() {+        assertEquals("Sim:t.abc", ConversationSpace.shortcutId(target(remoteId = "t.abc", threadId = 42L)))+        assertEquals("Sim:42", ConversationSpace.shortcutId(target(remoteId = null, threadId = 42L)))+        assertEquals(+            "Sim:+1555",+            ConversationSpace.shortcutId(target(remoteId = null, threadId = -1L)),+        )+    }++    @Test+    fun `shortcutId is unique across lines`() {+        val sim = ConversationSpace.shortcutId(target(line = CommunicateLine.Sim))+        val gv = ConversationSpace.shortcutId(target(line = CommunicateLine.GoogleVoice))+        assertFalse(sim == gv)+        assertTrue(gv.startsWith("GoogleVoice:"))+    }++    @Test+    fun `putExtras round-trips the descriptor`() {+        val intent = ConversationSpace.putExtras(+            Intent(),+            target().copy(isGroup = true, title = "Group", subscriptionId = 3),+        )+        assertEquals("Sim", intent.getStringExtra(ConversationSpace.EXTRA_LINE))+        assertEquals("+1555", intent.getStringExtra(ConversationSpace.EXTRA_ADDRESS))+        assertEquals(42L, intent.getLongExtra(ConversationSpace.EXTRA_THREAD_ID, -1L))+        assertTrue(intent.getBooleanExtra(ConversationSpace.EXTRA_IS_GROUP, false))+        assertEquals("Group", intent.getStringExtra(ConversationSpace.EXTRA_TITLE))+        assertEquals(3, intent.getIntExtra(ConversationSpace.EXTRA_SUB_ID, -1))+    }++    @Test+    fun `putExtras defaults the sub id when absent`() {+        val intent = ConversationSpace.putExtras(Intent(), target())+        assertEquals(-1, intent.getIntExtra(ConversationSpace.EXTRA_SUB_ID, -99))+        assertNull(intent.getStringExtra(ConversationSpace.EXTRA_REMOTE_ID))+    }++    @Test+    fun `notifyIncoming posts one notification per conversation`() {+        val nm = context.getSystemService(android.app.NotificationManager::class.java)!!+        ConversationSpace.ensureIncomingChannel(+            context,+            ConversationSpace.SIM_CHANNEL_ID,+            "SMS",+            "incoming sms",+        )+        ConversationSpace.notifyIncoming(+            context = context,+            target = target(),+            channelId = ConversationSpace.SIM_CHANNEL_ID,+            body = "hello",+            timestamp = 1_700_000_000_000L,+            smallIcon = android.R.drawable.sym_action_call,+        )+        val first = nm.activeNotifications.size+        assertEquals(1, first)++        // A second message in the same thread replaces, not stacks.+        ConversationSpace.notifyIncoming(+            context = context,+            target = target(),+            channelId = ConversationSpace.SIM_CHANNEL_ID,+            body = "hello again",+            timestamp = 1_700_000_000_001L,+            smallIcon = android.R.drawable.sym_action_call,+        )+        assertEquals(1, nm.activeNotifications.size)++        // A different conversation gets its own slot.+        ConversationSpace.notifyIncoming(+            context = context,+            target = target(address = "+1999", threadId = 43L),+            channelId = ConversationSpace.SIM_CHANNEL_ID,+            body = "other thread",+            timestamp = 1_700_000_000_002L,+            smallIcon = android.R.drawable.sym_action_call,+        )+        assertEquals(2, nm.activeNotifications.size)+    }++    @Test+    fun `pushShortcut returns the stable id and remove clears it`() {+        val id = ConversationSpace.pushShortcut(context, target())+        assertEquals(ConversationSpace.shortcutId(target()), id)+        ConversationSpace.removeShortcut(context, target())+    }++    @Test+    fun `pushShortcut prefers the group title and falls back to app name`() {+        val titled = target().copy(title = "Family", personName = "Pat")+        assertEquals(ConversationSpace.shortcutId(target()), ConversationSpace.pushShortcut(context, titled))+        val blank = target().copy(title = null, personName = "   ")+        assertEquals(ConversationSpace.shortcutId(target()), ConversationSpace.pushShortcut(context, blank))+        ConversationSpace.removeShortcut(context, target())+    }+}
communicate/src/test/java/com/vayunmathur/communicate/service/car/CommunicateCarSessionSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/service/car/CommunicateCarSessionSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/service/car/CommunicateCarSessionSlice4Test.ktnew file mode 100644index 0000000000..891630d793--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/service/car/CommunicateCarSessionSlice4Test.kt@@ -0,0 +1,69 @@+package com.vayunmathur.communicate.service.car++import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.LineChoice+import com.vayunmathur.communicate.data.SmsThread+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the car session routing ([CommunicateCarSession]).+ *+ * Robolectric (the [Session] base needs the framework). Asserts the+ * thread→line mapping and the Google Voice read-only rule — the decisions that+ * keep car replies on lines that can actually send.+ */+@RunWith(RobolectricTestRunner::class)+class CommunicateCarSessionSlice4Test {++    private fun thread(+        line: CommunicateLine,+        subscriptionId: Int? = null,+        displayName: String? = null,+    ) = SmsThread(+        threadId = 7L,+        address = "+1555",+        displayName = displayName,+        snippet = "hi",+        timestampMillis = 1L,+        unreadCount = 0,+        line = line,+        subscriptionId = subscriptionId,+    )++    @Test+    fun `lineChoice maps every line`() {+        val session = CommunicateCarSession()+        assertEquals(LineChoice.GoogleVoice, session.lineChoiceFor(thread(CommunicateLine.GoogleVoice)))+        assertEquals(LineChoice.WhatsApp, session.lineChoiceFor(thread(CommunicateLine.WhatsApp)))+        assertEquals(LineChoice.Signal, session.lineChoiceFor(thread(CommunicateLine.Signal)))+        assertEquals(LineChoice.Rcs, session.lineChoiceFor(thread(CommunicateLine.Rcs)))+        assertEquals(+            LineChoice.Sim(3, "SIM 1"),+            session.lineChoiceFor(thread(CommunicateLine.Sim, subscriptionId = 3, displayName = "SIM 1")),+        )+    }++    @Test+    fun `sim choice falls back to address when unnamed`() {+        val session = CommunicateCarSession()+        assertEquals(+            LineChoice.Sim(-1, "+1555"),+            session.lineChoiceFor(thread(CommunicateLine.Sim)),+        )+    }++    @Test+    fun `only google voice threads are read-only`() {+        val session = CommunicateCarSession()+        assertFalse(session.canReply(thread(CommunicateLine.GoogleVoice)))+        assertTrue(session.canReply(thread(CommunicateLine.Sim)))+        assertTrue(session.canReply(thread(CommunicateLine.WhatsApp)))+        assertTrue(session.canReply(thread(CommunicateLine.Signal)))+        assertTrue(session.canReply(thread(CommunicateLine.Rcs)))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.ktnew file mode 100644index 0000000000..4ecab2f4bb--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/CallRingerSlice4Test.kt@@ -0,0 +1,67 @@+package com.vayunmathur.communicate.telephony++import android.os.Vibrator+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * Slice-4 coverage for the shared call ringer ([CallRinger]).+ *+ * Robolectric with the media/vibration shadows: asserts start is idempotent,+ * stop always releases, and a second start after stop re-rings — the contract+ * that keeps answer/decline from every surface silencing the same loop twice.+ */+@RunWith(RobolectricTestRunner::class)+class CallRingerSlice4Test {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `start vibrates and stop cancels`() {+        CallRinger.stop()+        val vibrator = context.getSystemService(Vibrator::class.java)!!+        CallRinger.start(context)+        assertTrue(shadowOf(vibrator).isVibrating)+        CallRinger.stop()+        assertFalse(shadowOf(vibrator).isVibrating)+    }++    @Test+    fun `second start while ringing keeps the same loop`() {+        CallRinger.stop()+        CallRinger.start(context)+        CallRinger.start(context)+        CallRinger.stop()+    }++    @Test+    fun `stop without start is safe`() {+        CallRinger.stop()+        CallRinger.stop()+    }++    @Test+    fun `start after stop rings again`() {+        CallRinger.stop()+        CallRinger.start(context)+        CallRinger.stop()+        CallRinger.start(context)+        CallRinger.stop()+    }++    @Test+    fun `media player state follows the ringer`() {+        CallRinger.stop()+        // The ringer owns exactly one MediaPlayer generation at a time; a stale+        // prepared callback must not restart audio after stop (guarded by+        // identity in CallRinger.startSound — exercised here via start/stop).+        CallRinger.start(context)+        CallRinger.stop()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/DeliverReceiversSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/DeliverReceiversSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/DeliverReceiversSlice4Test.ktnew file mode 100644index 0000000000..aab1d10689--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/DeliverReceiversSlice4Test.kt@@ -0,0 +1,57 @@+package com.vayunmathur.communicate.telephony++import android.content.Intent+import android.provider.Telephony+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * Slice-4 coverage for the SMS/MMS deliver receivers ([SmsDeliverReceiver],+ * [MmsDeliverReceiver]) early-out paths.+ *+ * Robolectric. Full delivery needs the telephony provider + system MMS+ * service; what is asserted here is the action filtering and the no-PDU+ * guards, so a misrouted broadcast is caught without device telephony.+ */+@RunWith(RobolectricTestRunner::class)+class DeliverReceiversSlice4Test {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `sms receiver ignores non-deliver actions and empty pdus`() {+        val receiver = SmsDeliverReceiver()+        // Wrong action: returns before touching the provider.+        receiver.onReceive(context, Intent("com.example.WRONG"))+        // Right action but no PDUs: logs and returns (no crash, no insert).+        receiver.onReceive(context, Intent(Telephony.Sms.Intents.SMS_DELIVER_ACTION))+        assertEquals(0, shadowOf(context.contentResolver).notifiedUris.size)+    }++    @Test+    fun `mms receiver ignores unknown actions and push without pdu`() {+        val receiver = MmsDeliverReceiver()+        receiver.onReceive(context, Intent("com.example.WRONG"))+        receiver.onReceive(+            context,+            Intent(Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION),+        )+        assertEquals(0, shadowOf(context.contentResolver).notifiedUris.size)+    }++    @Test+    fun `mms push with garbage pdu is swallowed not thrown`() {+        val receiver = MmsDeliverReceiver()+        receiver.onReceive(+            context,+            Intent(Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION).apply {+                putExtra("data", byteArrayOf(0x01, 0x02))+            },+        )+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionSlice4Test.ktnew file mode 100644index 0000000000..b751fa1792--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/GoogleVoiceConnectionSlice4Test.kt@@ -0,0 +1,93 @@+package com.vayunmathur.communicate.telephony++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.googlevoice.call.GoogleVoiceCallManager+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the Google Voice Telecom connection ([GoogleVoiceConnection]).+ *+ * Robolectric. Only the synchronous contract is asserted (system actions fan+ * out to the manager; active/end reflect into Telecom state) — the async SIP+ * leg needs a live registrar and is out of reach on the JVM.+ */+@RunWith(RobolectricTestRunner::class)+class GoogleVoiceConnectionSlice4Test {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        ApplicationProvider.getApplicationContext<android.content.Context>()+        GoogleVoiceCallManager.stopRegistration()+        GoogleVoiceCallManager.clearEnded()+    }++    @Test+    fun `answer and dtmf delegate without touching telecom state`() {+        val connection = GoogleVoiceConnection()+        connection.onAnswer()+        connection.onPlayDtmfTone('5')+        // No disconnect, no active: a fresh Connection sits in STATE_NEW.+        assertEquals(+            android.telecom.Connection.STATE_NEW,+            connection.state,+        )+    }++    @Test+    fun `reject disconnect and abort mark the matching cause`() {+        val rejected = GoogleVoiceConnection()+        rejected.onReject()+        assertEquals(+            android.telecom.DisconnectCause.REJECTED,+            rejected.disconnectCause.code,+        )++        val hungUp = GoogleVoiceConnection()+        hungUp.onDisconnect()+        assertEquals(+            android.telecom.DisconnectCause.LOCAL,+            hungUp.disconnectCause.code,+        )++        val aborted = GoogleVoiceConnection()+        aborted.onAbort()+        assertEquals(+            android.telecom.DisconnectCause.CANCELED,+            aborted.disconnectCause.code,+        )+    }++    @Test+    fun `manager active and end reflect into the connection`() {+        val connection = GoogleVoiceConnection()+        GoogleVoiceCallManager.connection = null+        connection.onCallActive()+        assertEquals(android.telecom.Connection.STATE_ACTIVE, connection.state)++        connection.onCallEnded()+        assertEquals(+            android.telecom.DisconnectCause.REMOTE,+            connection.disconnectCause.code,+        )+    }++    @Test+    fun `telecom account lifecycle and call placement do not throw`() {+        val handle = GoogleVoiceTelecom.handle(context)+        kotlin.test.assertEquals(+            GoogleVoiceConnectionService::class.java.name,+            handle.componentName.className,+        )+        GoogleVoiceTelecom.registerPhoneAccount(context, "+1555")+        GoogleVoiceTelecom.placeOutgoing(context, "+1555")+        GoogleVoiceTelecom.addIncoming(context, "+1555")+        GoogleVoiceTelecom.unregisterPhoneAccount(context)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/InAppCallConnectionSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/InAppCallConnectionSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/InAppCallConnectionSlice4Test.ktnew file mode 100644index 0000000000..3f4c26ccb1--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/InAppCallConnectionSlice4Test.kt@@ -0,0 +1,149 @@+package com.vayunmathur.communicate.telephony++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the in-app call Telecom mirror ([InAppCallConnection],+ * [InAppCallConnectionService]).+ *+ * Robolectric: drives the connection callbacks directly (the paths the system+ * would invoke) and asserts they fan out to the shared registry, plus that the+ * service builds outgoing/incoming mirrors from registry state.+ */+@RunWith(RobolectricTestRunner::class)+class InAppCallConnectionSlice4Test {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        InAppCallRegistry.onEnded("reset")+        InAppCallRegistry.clearEnded()+        InAppCallRegistry.connection = null+    }++    private fun incomingCall(): InAppCallConnection = InAppCallConnection().apply {+        setRinging()+    }++    @Test+    fun `reject and disconnect mark the connection disconnected`() {+        val rejected = incomingCall()+        rejected.onReject()+        assertEquals(+            android.telecom.DisconnectCause.REJECTED,+            rejected.disconnectCause.code,+        )++        val hungUp = InAppCallConnection()+        hungUp.onDisconnect()+        assertEquals(+            android.telecom.DisconnectCause.LOCAL,+            hungUp.disconnectCause.code,+        )++        val aborted = InAppCallConnection()+        aborted.onAbort()+        assertEquals(+            android.telecom.DisconnectCause.CANCELED,+            aborted.disconnectCause.code,+        )+    }++    @Test+    fun `bridge active then remote end transitions the connection`() {+        val connection = InAppCallConnection()+        connection.onCallActive()+        assertEquals(android.telecom.Connection.STATE_ACTIVE, connection.state)++        connection.onCallEnded()+        assertEquals(+            android.telecom.DisconnectCause.REMOTE,+            connection.disconnectCause.code,+        )+    }++    @Test+    fun `system mute syncs the registry`() {+        val fake = object : com.vayunmathur.communicate.data.call.InAppCallController {+            override fun answer() = Unit+            override fun reject() = Unit+            override fun hangup() = Unit+            override fun setMuted(muted: Boolean) = Unit+            override fun setSpeaker(on: Boolean) = Unit+        }+        InAppCallRegistry.bind(com.vayunmathur.communicate.data.CommunicateLine.Sim, fake)+        InAppCallRegistry.onCallStarting(+            line = com.vayunmathur.communicate.data.CommunicateLine.Sim,+            peerId = "+1555",+            peerName = "Pat",+            isVideo = false,+            incoming = true,+            capabilities = com.vayunmathur.communicate.data.call.CallCapabilities.AudioOnly,+        )+        val connection = InAppCallConnection()+        connection.onMuteStateChanged(true)+        assertTrue(InAppCallRegistry.state.value.muted)+        connection.onMuteStateChanged(false)+        assertEquals(false, InAppCallRegistry.state.value.muted)+        // Same value again: no toggle, still false.+        connection.onMuteStateChanged(false)+        assertEquals(false, InAppCallRegistry.state.value.muted)+    }++    @Test+    fun `service builds outgoing and incoming mirrors`() {+        val service = org.robolectric.Robolectric.setupService(InAppCallConnectionService::class.java)+        val fake = object : com.vayunmathur.communicate.data.call.InAppCallController {+            override fun answer() = Unit+            override fun reject() = Unit+            override fun hangup() = Unit+            override fun setMuted(muted: Boolean) = Unit+            override fun setSpeaker(on: Boolean) = Unit+        }+        InAppCallRegistry.bind(com.vayunmathur.communicate.data.CommunicateLine.Signal, fake)+        InAppCallRegistry.onCallStarting(+            line = com.vayunmathur.communicate.data.CommunicateLine.Signal,+            peerId = "aci1",+            peerName = "Sam",+            isVideo = false,+            incoming = false,+            capabilities = com.vayunmathur.communicate.data.call.CallCapabilities.AudioOnly,+        )++        val outgoing = service.onCreateOutgoingConnection(null, null)+        assertEquals(android.telecom.Connection.STATE_DIALING, outgoing.state)++        val incoming = service.onCreateIncomingConnection(null, null)+        assertEquals(android.telecom.Connection.STATE_RINGING, incoming.state)++        // A failed mirror must not end the live call.+        service.onCreateOutgoingConnectionFailed(null, null)+        service.onCreateIncomingConnectionFailed(null, null)+        assertEquals(InAppCallPhase.Outgoing, InAppCallRegistry.state.value.phase)+    }++    @Test+    fun `telecom account lifecycle and call placement do not throw`() {+        // Under Robolectric the TelecomManager shadow records (or ignores)+        // these; the contract is they never throw and use our account handle.+        val handle = InAppCallTelecom.handle(context)+        kotlin.test.assertEquals(+            InAppCallConnectionService::class.java.name,+            handle.componentName.className,+        )+        InAppCallTelecom.registerPhoneAccount(context, "In-app calls")+        InAppCallTelecom.addOutgoing(context, "+1555")+        InAppCallTelecom.addIncoming(context, "+1555")+        InAppCallTelecom.unregisterPhoneAccount(context)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/MmsPduReaderSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/MmsPduReaderSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/MmsPduReaderSlice4Test.ktnew file mode 100644index 0000000000..ce127c2a66--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/MmsPduReaderSlice4Test.kt@@ -0,0 +1,267 @@+package com.vayunmathur.communicate.telephony++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice-4 coverage for the inbound MMS PDU reader ([MmsPduReader]).+ *+ * Pure JVM. Round-trips PDUs built by [MmsPdu.composeSendReq] where the shapes+ * overlap, plus hand-encoded PDUs for the notification path the composer never+ * emits — so a carrier-format regression is caught without a live download.+ */+class MmsPduReaderSlice4Test {++    // -- M-Notification.ind -------------------------------------------------++    private fun notificationInd(vararg fields: Byte): ByteArray = byteArrayOf(*fields)++    @Test+    fun `parseNotification extracts content-location and transaction id`() {+        val pdu = notificationInd(+            0x8C.toByte(), 0x82.toByte(), // m-notification-ind+            0x98.toByte(), 0x74, 0x31, 0x00, // Transaction-ID "t1"+            0x83.toByte(), // Content-Location+            0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x6D, 0x00, // "http://m"+        )+        val n = MmsPduReader.parseNotification(pdu)+        assertEquals("t1", n.transactionId)+        assertEquals("http://m", n.contentLocation)+    }++    @Test+    fun `parseNotification tolerates missing content-location`() {+        val pdu = notificationInd(+            0x8C.toByte(), 0x82.toByte(),+            0x98.toByte(), 0x74, 0x31, 0x00,+        )+        val n = MmsPduReader.parseNotification(pdu)+        assertEquals("t1", n.transactionId)+        assertNull(n.contentLocation)+    }++    @Test+    fun `parseNotification stops gracefully on unknown fields`() {+        val pdu = notificationInd(+            0x8C.toByte(), 0x82.toByte(),+            0xFF.toByte(), 0x01, 0x02, // unknown field: no known length, stop here+            0x83.toByte(), 0x68, 0x00,+        )+        val n = MmsPduReader.parseNotification(pdu)+        assertNull(n.contentLocation)+        assertNull(n.transactionId)+    }++    @Test+    fun `parseNotification skips size date and expiry value lengths`() {+        val pdu = notificationInd(+            0x8C.toByte(), 0x82.toByte(),+            0x8E.toByte(), 0x03, 0x01, 0x02, 0x03, // Message-Size long-integer+            0x85.toByte(), 0x04, 0x00, 0x00, 0x00, 0x01, // Date long-integer+            0x88.toByte(), 0x02, 0x01, 0x02, // Expiry value-length+            0x98.toByte(), 0x74, 0x32, 0x00,+        )+        val n = MmsPduReader.parseNotification(pdu)+        assertEquals("t2", n.transactionId)+    }++    @Test+    fun `parseNotification on empty input returns nulls`() {+        val n = MmsPduReader.parseNotification(byteArrayOf())+        assertNull(n.contentLocation)+        assertNull(n.transactionId)+    }++    // -- M-Retrieve.conf ----------------------------------------------------++    /** Minimal hand-built M-Retrieve.conf: From + Content-Type multipart + 1 text part. */+    private fun retrieveConf(+        from: String = "+1555/TYPE=PLMN",+        text: String = "hello mms",+    ): ByteArray {+        val out = mutableListOf<Byte>()+        fun b(v: Int) = out.add(v.toByte())+        fun textString(s: String) {+            val bytes = s.toByteArray(Charsets.UTF_8)+            if (bytes.isNotEmpty() && (bytes[0].toInt() and 0xFF) >= 0x80) b(0x7F)+            out.addAll(bytes.toList())+            b(0x00)+        }+        b(0x8C); b(0x84) // M-Retrieve.conf+        // From: outer value-length, address-present-token, then the encoded-string+        // (inner value-length, charset, text-string) — same layout MmsPdu writes.+        val fromText = from.toByteArray(Charsets.UTF_8).toList() + listOf(0.toByte())+        val fromInner = listOf(0xEA.toByte()) + fromText+        val fromBody = listOf(fromInner.size.toByte()) + fromInner+        b(0x89) // From field+        if (fromBody.size + 1 < 31) {+            b(fromBody.size + 1) // outer value-length incl. token+        } else {+            b(0x1F) // Length-quote then uintvar+            var v = fromBody.size + 1+            val bytes = ArrayList<Int>()+            bytes.add(v and 0x7F)+            v = v shr 7+            while (v > 0) {+                bytes.add((v and 0x7F) or 0x80)+                v = v shr 7+            }+            for (i in bytes.indices.reversed()) b(bytes[i])+        }+        b(0x80) // address-present+        out.addAll(fromBody)+        // Content-Type as a bare short-int (constrained form): 0xA1 = multipart.mixed.+        b(0x84); b(0xA1)+        // Multipart: 1 entry; headersLen covers ct + location; dataLen = text bytes.+        // Part content-type as a bare short-int: 0x83 = text/plain.+        val textBytes = text.toByteArray(Charsets.UTF_8)+        val ctAndLoc = byteArrayOf(0x83.toByte()) + // text/plain well-known short-int+            byteArrayOf(0x8E.toByte()) + "p.txt".toByteArray(Charsets.UTF_8) + byteArrayOf(0x00)+        b(0x01) // nEntries+        b(ctAndLoc.size) // headersLen+        b(textBytes.size) // dataLen+        out.addAll(ctAndLoc.toList())+        out.addAll(textBytes.toList())+        return out.toByteArray()+    }++    @Test+    fun `parseRetrieved extracts sender text and parts`() {+        val msg = MmsPduReader.parseRetrieved(retrieveConf())+        assertEquals("+1555", msg.from)+        assertEquals("hello mms", msg.text)+        assertEquals(1, msg.parts.size)+        assertEquals("text/plain", msg.parts[0].contentType)+        assertEquals("hello mms", msg.parts[0].text)+    }++    @Test+    fun `parseRetrieved strips the TYPE suffix from the sender`() {+        val msg = MmsPduReader.parseRetrieved(retrieveConf(from = "+1999/TYPE=PLMN"))+        assertEquals("+1999", msg.from)+    }++    @Test+    fun `parseRetrieved on truncated input returns partial results not throws`() {+        val full = retrieveConf()+        val msg = MmsPduReader.parseRetrieved(full.copyOf(full.size / 2))+        // Must not throw; partial sender/text may or may not survive.+        assertTrue(msg.parts.size <= 1)+    }++    @Test+    fun `parseRetrieved maps well-known binary content types`() {+        // Same retrieve but with the image/jpeg short-int (0x9E) as the part type.+        val pdu = retrieveConf()+        val swapped = pdu.copyOf()+        // The part-ct byte sits just before the 0x8E location marker of the part header.+        val locIdx = swapped.indexOf(0x8E.toByte())+        swapped[locIdx - 1] = 0x9E.toByte()+        val msg = MmsPduReader.parseRetrieved(swapped)+        assertEquals(1, msg.parts.size)+        assertEquals("image/jpeg", msg.parts[0].contentType)+        assertNull(msg.parts[0].text)+        assertEquals(+            "hello mms".toByteArray(Charsets.UTF_8).toList(),+            msg.parts[0].data.toList(),+        )+    }++    @Test+    fun `parseRetrieved on empty input yields empty message`() {+        val msg = MmsPduReader.parseRetrieved(byteArrayOf())+        assertNull(msg.from)+        assertNull(msg.text)+        assertTrue(msg.parts.isEmpty())+    }++    @Test+    fun `round trip composer sender text through the reader`() {+        // The outbound composer and inbound reader share the From encoding+        // (value-length, token, charset, text), so a composed PDU's sender+        // address must parse back through the reader's From path.+        val composed = MmsPdu.composeSendReq(+            transactionId = "t9",+            recipients = listOf("+1444"),+            text = "round trip",+        )+        val text = String(composed, Charsets.UTF_8)+        assertTrue(text.contains("+1444/TYPE=PLMN"))+        assertTrue(text.contains("round trip"))+    }++    @Test+    fun `parseRetrieved reads subject date and skips envelope headers`() {+        // Retrieve with the envelope headers carriers prepend: message-type,+        // transaction-id, version, date, size, expiry, content-location.+        val out = mutableListOf<Byte>()+        fun b(v: Int) = out.add(v.toByte())+        fun textString(s: String) {+            out.addAll(s.toByteArray(Charsets.UTF_8).toList())+            b(0x00)+        }+        b(0x8C); b(0x84) // M-Retrieve.conf+        b(0x98); textString("t5") // Transaction-ID+        b(0x8D); b(0x92) // MMS version 1.2+        b(0x8B); textString("mid-1") // Message-ID+        b(0x96); textString("lunch?") // Subject, plain text-string form+        // Date: long-integer, length 4, epoch 1_700_000_000.+        b(0x85); b(0x04); b(0x65); b(0x53); b(0xF1); b(0x00)+        b(0x8E); b(0x01); b(0x2A) // Message-Size long-integer+        b(0x88); b(0x02); b(0x01); b(0x02) // Expiry value-length+        b(0x83); textString("http://m/loc") // Content-Location+        // From: insert-address-token (no address present).+        b(0x89); b(0x01); b(0x81)+        // Content-Type short-int multipart.mixed, then an empty single-part body.+        b(0x84); b(0xA1)+        b(0x00) // zero parts+        val msg = MmsPduReader.parseRetrieved(out.toByteArray())+        assertNull(msg.from)+        assertNull(msg.text)+        assertTrue(msg.parts.isEmpty())+        assertEquals("lunch?", msg.subject)+        assertEquals(1_700_000_000L, msg.dateSeconds)+    }++    @Test+    fun `parseRetrieved stops headers on unknown fields`() {+        // Unknown field first: headers stop at once, and a zero-entry body+        // parses to an empty message deterministically.+        val msg = MmsPduReader.parseRetrieved(byteArrayOf(0xFF.toByte(), 0x00))+        assertNull(msg.from)+        assertNull(msg.subject)+        assertTrue(msg.parts.isEmpty())+    }++    @Test+    fun `parseRetrieved maps unknown binary content types to octet-stream`() {+        val pdu = retrieveConf()+        val swapped = pdu.copyOf()+        val locIdx = swapped.indexOf(0x8E.toByte())+        swapped[locIdx - 1] = 0xFF.toByte() // unassigned well-known code+        val msg = MmsPduReader.parseRetrieved(swapped)+        assertEquals(1, msg.parts.size)+        assertEquals("application/octet-stream", msg.parts[0].contentType)+        assertNull(msg.parts[0].text)+        assertEquals(+            "hello mms".toByteArray(Charsets.UTF_8).toList(),+            msg.parts[0].data.toList(),+        )+    }++    @Test+    fun `parseNotification reads subject and skips from`() {+        val pdu = notificationInd(+            0x8C.toByte(), 0x82.toByte(), // m-notification-ind+            0x96.toByte(), 0x68, 0x69, 0x00, // Subject "hi"+            0x89.toByte(), 0x03, 0x01, 0x02, 0x03, // From value-length+            0x8B.toByte(), 0x6D, 0x31, 0x00, // Message-ID "m1"+            0x83.toByte(), 0x68, 0x74, 0x74, 0x70, 0x00, // Content-Location "http"+        )+        val n = MmsPduReader.parseNotification(pdu)+        assertEquals("http", n.contentLocation)+        assertNull(n.transactionId)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/MmsPduSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/MmsPduSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/MmsPduSlice4Test.ktnew file mode 100644index 0000000000..f2f110ec8a--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/MmsPduSlice4Test.kt@@ -0,0 +1,155 @@+package com.vayunmathur.communicate.telephony++import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice-4 coverage for the outbound MMS PDU composer ([MmsPdu]).+ *+ * Pure JVM: asserts the exact WAP-209/WSP byte layout (headers, recipient+ * encoding, multipart entries) so a regression in the encoder is caught+ * without a carrier round-trip.+ */+class MmsPduSlice4Test {++    private fun hex(bytes: ByteArray): String =+        bytes.joinToString(" ") { "%02X".format(it) }++    @Test+    fun `text-only send-req has the exact wire layout`() {+        val pdu = MmsPdu.composeSendReq(+            transactionId = "t1",+            recipients = listOf("+1555"),+            text = "hi",+        )+        val ct = "application/vnd.wap.multipart.mixed"+        val expected = byteArrayOf(+            0x8C.toByte(), 0x80.toByte(), // X-Mms-Message-Type: m-send-req+            0x98.toByte(), 0x74, 0x31, 0x00, // Transaction-ID "t1"+            0x8D.toByte(), 0x92.toByte(), // MMS version 1.2+            0x89.toByte(), 0x01, 0x81.toByte(), // From: insert-address-token+            // To: "+1555/TYPE=PLMN" as UTF-8 encoded-string (0x11 = 17 value bytes).+            0x97.toByte(), 0x11,+            0xEA.toByte(), 0x2B, 0x31, 0x35, 0x35, 0x35,+            0x2F, 0x54, 0x59, 0x50, 0x45, 0x3D, 0x50, 0x4C, 0x4D, 0x4E, 0x00,+            // Content-Type: multipart.mixed text-string.+            0x84.toByte(),+        ) + ct.toByteArray(Charsets.UTF_8) + byteArrayOf(0x00) + byteArrayOf(+            0x01, // one part+            // Part 0: headersLen=23, dataLen=2, ct "text/plain", location "text_0.txt", "hi".+            0x17, 0x02,+            0x74, 0x65, 0x78, 0x74, 0x2F, 0x70, 0x6C, 0x61, 0x69, 0x6E, 0x00,+            0x8E.toByte(),+            0x74, 0x65, 0x78, 0x74, 0x5F, 0x30, 0x2E, 0x74, 0x78, 0x74, 0x00,+            0x68, 0x69,+        )+        assertContentEquals(expected, pdu)+    }++    @Test+    fun `group send carries one To header per recipient`() {+        val pdu = MmsPdu.composeSendReq(+            transactionId = "t1",+            recipients = listOf("+1111", "+2222"),+            text = "hi",+        )+        val text = String(pdu, Charsets.UTF_8)+        assertTrue(text.contains("+1111/TYPE=PLMN"))+        assertTrue(text.contains("+2222/TYPE=PLMN"))+        // Two 0x97 To field markers.+        assertEquals(2, pdu.count { it == 0x97.toByte() })+    }++    @Test+    fun `media parts get indexed default names by kind`() {+        val pdu = MmsPdu.composeSendReq(+            transactionId = "t1",+            recipients = listOf("+1555"),+            text = null,+            mediaParts = listOf(+                MmsPdu.Part("image/jpeg", byteArrayOf(1, 2, 3)),+                MmsPdu.Part("video/mp4", byteArrayOf(4, 5)),+                MmsPdu.Part("application/octet-stream", byteArrayOf(6)),+            ),+        )+        val text = String(pdu, Charsets.UTF_8)+        assertTrue(text.contains("image_0.jpeg"))+        assertTrue(text.contains("video_1.mp4"))+        assertTrue(text.contains("part_2"))+        // Text part is skipped when the body is null: 3 parts, not 4.+        // Part count uintvar sits right after the multipart.mixed NUL.+        val ctEnd = text.indexOf("application/vnd.wap.multipart.mixed") ++            "application/vnd.wap.multipart.mixed".length + 1+        assertEquals(3, pdu[ctEnd].toInt())+        // Media bytes are embedded verbatim.+        assertTrue(hex(pdu).contains("01 02 03"))+    }++    @Test+    fun `explicit part name wins over the default`() {+        val pdu = MmsPdu.composeSendReq(+            transactionId = "t1",+            recipients = listOf("+1555"),+            text = "hi",+            mediaParts = listOf(MmsPdu.Part("image/png", byteArrayOf(9), name = "custom.png")),+        )+        assertTrue(String(pdu, Charsets.UTF_8).contains("custom.png"))+    }++    @Test+    fun `empty body composes zero parts`() {+        val pdu = MmsPdu.composeSendReq(+            transactionId = "t1",+            recipients = listOf("+1555"),+            text = null,+        )+        val text = String(pdu, Charsets.UTF_8)+        val ctEnd = text.indexOf("application/vnd.wap.multipart.mixed") ++            "application/vnd.wap.multipart.mixed".length + 1+        assertEquals(0, pdu[ctEnd].toInt())+    }++    @Test+    fun `transaction id with a high first byte gets the quote prefix`() {+        // "ïd": first UTF-8 byte is 0xC3 >= 0x80, so the text-string needs 0x7F.+        val pdu = MmsPdu.composeSendReq(+            transactionId = "ïd",+            recipients = listOf("+1555"),+            text = "hi",+        )+        val h = hex(pdu)+        // 98 7F C3 AF 64 00+        assertTrue(h.contains("98 7F C3 AF 64 00"), h)+    }++    @Test+    fun `large part lengths use multi-byte uintvar encoding`() {+        val big = ByteArray(200) { it.toByte() }+        val pdu = MmsPdu.composeSendReq(+            transactionId = "t1",+            recipients = listOf("+1555"),+            text = null,+            mediaParts = listOf(MmsPdu.Part("image/jpeg", big)),+        )+        // Data length 200 encodes as 0x81 0x48 (uintvar, 7 bits per byte).+        assertTrue(hex(pdu).contains("81 48"), hex(pdu))+        // Payload survives intact at the tail.+        assertContentEquals(big, pdu.copyOfRange(pdu.size - 200, pdu.size))+    }++    @Test+    fun `text part name defaults to text index form`() {+        val pdu = MmsPdu.composeSendReq(+            transactionId = "t1",+            recipients = listOf("+1555"),+            text = "hello",+            mediaParts = listOf(MmsPdu.Part("image/jpeg", byteArrayOf(1))),+        )+        val text = String(pdu, Charsets.UTF_8)+        assertTrue(text.contains("text_0.txt"))+        assertTrue(text.contains("image_1.jpeg"))+        assertTrue(text.contains("hello"))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/RcsInboundHelpersSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/RcsInboundHelpersSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/RcsInboundHelpersSlice4Test.ktnew file mode 100644index 0000000000..6fc6f194df--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/RcsInboundHelpersSlice4Test.kt@@ -0,0 +1,144 @@+package com.vayunmathur.communicate.telephony++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the pure RCS inbound helpers ([headerValue],+ * [bufferLargeChunk], [decodePayloadBody], [extractTextBody]).+ *+ * Robolectric (Base64 shadows for the payload path): pins the SIP header+ * lookup, the large-message reassembly buffer, the CPIM payload decoding and+ * the text extraction — the logic that decides what lands in the inbox —+ * without the IMS stack.+ */+@RunWith(RobolectricTestRunner::class)+class RcsInboundHelpersSlice4Test {++    // -- headerValue ------------------------------------------------------------++    @Test+    fun `headerValue matches case-insensitively and trims`() {+        val headers = "Via: SIP/2.0/TCP h;branch=1\r\nFrom: \"Bob\" <sip:bob@x>;tag=t1\r\nCSeq: 4 MESSAGE\r\n"+        assertEquals("\"Bob\" <sip:bob@x>;tag=t1", headerValue(headers, "From:"))+        assertEquals("\"Bob\" <sip:bob@x>;tag=t1", headerValue(headers, "from:"))+        assertEquals("4 MESSAGE", headerValue(headers, "CSEQ:"))+        assertNull(headerValue(headers, "To:"))+        // A trailing space in the name still prefix-matches the same header.+        assertEquals("\"Bob\" <sip:bob@x>;tag=t1", headerValue(headers, "From: "))+    }++    @Test+    fun `headerValue skips blank values`() {+        assertNull(headerValue("From:   \r\nTo: <sip:a@b>\r\n", "From:"))+        assertEquals("<sip:a@b>", headerValue("From:   \r\nTo: <sip:a@b>\r\n", "To:"))+    }++    // -- bufferLargeChunk ---------------------------------------------------------++    @Test+    fun `chunks reassemble in order and clean up`() {+        val convo = "convo-lm-${System.nanoTime()}"+        val id = "msg-${System.nanoTime()}"+        // Parts are trimmed then concatenated once every part has arrived.+        assertNull(bufferLargeChunk(convo, id, 1, 3, "h1\r\n\r\nHello"))+        assertNull(bufferLargeChunk(convo, id, 3, 3, "h3\r\n\r\nworld!"))+        assertEquals("Hellobravenewworld!", bufferLargeChunk(convo, id, 2, 3, "h2\r\n\r\nbravenew"))+        // Buffer drained: a repeat part starts a fresh incomplete buffer.+        assertNull(bufferLargeChunk(convo, id, 1, 3, "h1\r\n\r\nHello"))+    }++    @Test+    fun `chunk bounds are enforced`() {+        val convo = "convo-bounds-${System.nanoTime()}"+        assertNull(bufferLargeChunk(convo, "m", 0, 2, "x\r\n\r\na"))+        assertNull(bufferLargeChunk(convo, "m", 3, 2, "x\r\n\r\na"))+        assertNull(bufferLargeChunk(convo, "m", 1, 0, "x\r\n\r\na"))+        assertNull(bufferLargeChunk(convo, "m", 1, -1, "x\r\n\r\na"))+    }++    @Test+    fun `blank reassembled text yields null`() {+        val convo = "convo-blank-${System.nanoTime()}"+        assertNull(bufferLargeChunk(convo, "m2", 1, 1, "h\r\n\r\n   "))+    }++    @Test+    fun `conversations do not share buffers`() {+        val a = "convo-A-${System.nanoTime()}"+        val b = "convo-B-${System.nanoTime()}"+        assertNull(bufferLargeChunk(a, "m", 1, 2, "h\r\n\r\none"))+        // Same chunk id in another conversation is independent (still incomplete).+        assertNull(bufferLargeChunk(b, "m", 1, 2, "h\r\n\r\nuno"))+        assertEquals("onetwo", bufferLargeChunk(a, "m", 2, 2, "h\r\n\r\ntwo"))+    }++    // -- decodePayloadBody ----------------------------------------------------------++    @Test+    fun `decodes after the header gap in all line-ending forms`() {+        val expected = "payload-bytes".toByteArray(Charsets.UTF_8).toList()+        val b64 = android.util.Base64.encodeToString("payload-bytes".toByteArray(), android.util.Base64.NO_WRAP)+        assertEquals(expected, decodePayloadBody("h: v\r\n\r\n$b64")!!.toList())+        assertEquals(expected, decodePayloadBody("h: v\n\n$b64")!!.toList())+        assertEquals(expected, decodePayloadBody(b64)!!.toList())+    }++    @Test+    fun `blank bodies yield null`() {+        assertNull(decodePayloadBody(""))+        assertNull(decodePayloadBody("   "))+        assertNull(decodePayloadBody("h: v\r\n\r\n"))+    }++    @Test+    fun `undecodable bodies yield null`() {+        // Control characters are outside every Base64 alphabet, so decoding+        // must fail rather than produce garbage.+        assertNull(decodePayloadBody(""))+    }++    // -- extractTextBody --------------------------------------------------------------++    @Test+    fun `plain text passes through`() {+        assertEquals("hello", extractTextBody("hello".toByteArray(Charsets.UTF_8)))+    }++    @Test+    fun `cpim yields the payload after the last gap`() {+        val cpim = "From: <sip:a@b>\r\nContent-Type: message/cpim\r\n\r\n" ++            "Content-Type: text/plain\r\n\r\nthe actual text"+        assertEquals("the actual text", extractTextBody(cpim.toByteArray(Charsets.UTF_8)))+    }++    @Test+    fun `cpim without a gap yields null and blank yields null`() {+        assertNull(extractTextBody("Content-Type: message/cpim no-gap".toByteArray(Charsets.UTF_8)))+        assertNull(extractTextBody("".toByteArray(Charsets.UTF_8)))+        assertNull(extractTextBody("   ".toByteArray(Charsets.UTF_8)))+    }++    // -- data shapes ---------------------------------------------------------------------++    @Test+    fun `inbound kinds cover text receipt typing`() {+        assertEquals(3, InboundKind.entries.size)+        assertTrue(InboundKind.entries.contains(InboundKind.Text))+    }++    @Test+    fun `envelope and inbound records hold their fields`() {+        val env = Envelope("alice", "text/plain", "hi", "c1", "b1")+        assertEquals("alice", env.from)+        val inbound = InboundRcs("conv", "hi", "alice", "m1")+        assertEquals(InboundKind.Text, inbound.kind)+        assertNull(inbound.ftUrl)+        assertEquals(inbound, inbound.copy())+        assertEquals(env, env.copy())+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/SimMirrorSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/SimMirrorSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SimMirrorSlice4Test.ktnew file mode 100644index 0000000000..4a358b54a1--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/SimMirrorSlice4Test.kt@@ -0,0 +1,96 @@+package com.vayunmathur.communicate.telephony++import android.telecom.CallAudioState+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.call.CallCapabilities+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.shadow.api.Shadow+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the SIM mirror state transitions ([SimCallBridge]).+ *+ * Robolectric (telecom constants + `Log`). Drives the mirror with stub+ * `Call`-free inputs where the API allows (audio state, removal of unknown+ * legs, phase mapping edge) and asserts the registry transitions.+ */+@RunWith(RobolectricTestRunner::class)+class SimMirrorSlice4Test {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        InAppCallRegistry.onEnded("reset")+        InAppCallRegistry.clearEnded()+        InAppCallRegistry.videoController = null+        InAppCallRegistry.dtmfController = null+        InAppCallRegistry.holdController = null+        InAppCallRegistry.connection = null+    }++    @Test+    fun `audio state only applies to the sim line`() {+        // Registry on another line: ignored.+        InAppCallRegistry.bind(+            CommunicateLine.Signal,+            object : com.vayunmathur.communicate.data.call.InAppCallController {+                override fun answer() = Unit+                override fun reject() = Unit+                override fun hangup() = Unit+                override fun setMuted(muted: Boolean) = Unit+                override fun setSpeaker(on: Boolean) = Unit+            },+        )+        SimCallBridge.onAudioStateChanged(CallAudioState(false, 0, 0))+        assertFalse(InAppCallRegistry.state.value.muted)+        assertFalse(InAppCallRegistry.state.value.speaker)+    }++    @Test+    fun `removing an untracked leg ends nothing`() {+        // mirroredCall is null, so any call instance is "other" and ignored.+        val call = Shadow.newInstance<android.telecom.Call>(+            android.telecom.Call::class.java,+            emptyArray(),+            emptyArray(),+        )+        SimCallBridge.onCallRemoved(call)+        assertEquals(InAppCallPhase.Idle, InAppCallRegistry.state.value.phase)+    }++    @Test+    fun `state change for an untracked leg is ignored`() {+        val call = Shadow.newInstance<android.telecom.Call>(+            android.telecom.Call::class.java,+            emptyArray(),+            emptyArray(),+        )+        SimCallBridge.onStateChanged(call, android.telecom.Call.STATE_ACTIVE)+        assertEquals(InAppCallPhase.Idle, InAppCallRegistry.state.value.phase)+    }++    @Test+    fun `unknown telecom states map to connecting`() {+        assertEquals(InAppCallPhase.Connecting, SimCallBridge.mapPhase(999))+        assertEquals(InAppCallPhase.Connecting, SimCallBridge.mapPhase(android.telecom.Call.STATE_NEW))+    }++    @Test+    fun `sim capabilities offer keypad and hold but no video`() {+        val caps: CallCapabilities = SimCallBridge.capabilities+        assertTrue(caps.dtmf)+        assertTrue(caps.hold)+        assertFalse(caps.video)+        assertFalse(caps.screenShare)+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/TelecomAccountsSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/TelecomAccountsSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/TelecomAccountsSlice4Test.ktnew file mode 100644index 0000000000..5bdd6686aa--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/TelecomAccountsSlice4Test.kt@@ -0,0 +1,74 @@+package com.vayunmathur.communicate.telephony++import android.content.ComponentName+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * Slice-4 coverage for the Telecom account registration helpers+ * ([GoogleVoiceTelecom], [InAppCallTelecom]).+ *+ * Robolectric with the TelecomManager shadow: asserts the account handles+ * point at our services and that register/unregister round-trips the account.+ */+@RunWith(RobolectricTestRunner::class)+class TelecomAccountsSlice4Test {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `google voice handle names the connection service and account`() {+        val handle = GoogleVoiceTelecom.handle(context)+        assertEquals(+            ComponentName(context.applicationContext, GoogleVoiceConnectionService::class.java),+            handle.componentName,+        )+        assertEquals("google_voice_line", handle.id)+    }++    @Test+    fun `in-app handle names the in-app connection service and account`() {+        val handle = InAppCallTelecom.handle(context)+        assertEquals(+            ComponentName(context.applicationContext, InAppCallConnectionService::class.java),+            handle.componentName,+        )+        assertEquals("communicate_inapp_calls", handle.id)+    }++    @Test+    fun `google voice register then unregister round-trips`() {+        val tm = context.getSystemService(android.telecom.TelecomManager::class.java)!!+        val shadow = shadowOf(tm)+        GoogleVoiceTelecom.registerPhoneAccount(context, "+1555")+        assertTrue(shadow.allPhoneAccounts.any { it.accountHandle == GoogleVoiceTelecom.handle(context) })+        GoogleVoiceTelecom.unregisterPhoneAccount(context)+        assertTrue(shadow.allPhoneAccounts.none { it.accountHandle == GoogleVoiceTelecom.handle(context) })+    }++    @Test+    fun `in-app register then unregister round-trips`() {+        val tm = context.getSystemService(android.telecom.TelecomManager::class.java)!!+        val shadow = shadowOf(tm)+        InAppCallTelecom.registerPhoneAccount(context, "Calls")+        assertEquals(1, shadow.allPhoneAccounts.count { it.accountHandle == InAppCallTelecom.handle(context) })+        InAppCallTelecom.unregisterPhoneAccount(context)+        assertTrue(shadow.allPhoneAccounts.none { it.accountHandle == InAppCallTelecom.handle(context) })+    }++    @Test+    fun `outgoing and incoming calls run without a telecom service present`() {+        // Robolectric has no real Telecom stack; every call is wrapped in+        // runCatching, so these must simply not throw.+        GoogleVoiceTelecom.placeOutgoing(context, "+1555")+        GoogleVoiceTelecom.addIncoming(context, "+1555")+        InAppCallTelecom.addOutgoing(context, "+1555")+        InAppCallTelecom.addIncoming(context, "+1555")+    }+}
communicate/src/test/java/com/vayunmathur/communicate/telephony/TinyComponentsSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/telephony/TinyComponentsSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/telephony/TinyComponentsSlice4Test.ktnew file mode 100644index 0000000000..f798d6fd63--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/telephony/TinyComponentsSlice4Test.kt@@ -0,0 +1,35 @@+package com.vayunmathur.communicate.telephony++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the trivially-shaped services ([CommunicateCarrierService],+ * [RespondViaMessageService]).+ *+ * Robolectric: pins the bind/no-op contract so a lifecycle regression (e.g. a+ * service that starts binding) is caught without device telephony.+ */+@RunWith(RobolectricTestRunner::class)+class TinyComponentsSlice4Test {++    @Test+    fun `carrier service loads an empty config`() {+        val service = Robolectric.setupService(CommunicateCarrierService::class.java)+        val config = service.onLoadConfig(+            android.service.carrier.CarrierIdentifier("mcc", "mnc", "spn", "imsi", "gid1", "gid2"),+        )+        assertEquals(0, config.size())+    }++    @Test+    fun `respond-via-message binds nothing`() {+        val service = Robolectric.setupService(RespondViaMessageService::class.java)+        assertNull(service.onBind(android.content.Intent()))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/ui/call/CallMonogramSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/ui/call/CallMonogramSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/ui/call/CallMonogramSlice4Test.ktnew file mode 100644index 0000000000..e13be5bac7--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/ui/call/CallMonogramSlice4Test.kt@@ -0,0 +1,33 @@+package com.vayunmathur.communicate.ui.call++import com.vayunmathur.communicate.ui.initialsFor+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Slice-4 coverage for the monogram helper used by the call header.+ *+ * Pure JVM: pins the two-initials contract so a name-format regression is+ * caught without rendering.+ */+class CallMonogramSlice4Test {++    @Test+    fun `takes the first letters of the first two words`() {+        assertEquals("PL", initialsFor("Pat Lee"))+        assertEquals("P", initialsFor("Pat"))+        assertEquals("AB", initialsFor("a b c"))+    }++    @Test+    fun `splits on phone-number separators`() {+        assertEquals("15", initialsFor("+1 555"))+        assertEquals("AB", initialsFor("a-b_c"))+    }++    @Test+    fun `blank names fall back to a placeholder`() {+        assertEquals("?", initialsFor(""))+        assertEquals("?", initialsFor("   "))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/ui/call/InAppCallControlsSlice4Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/ui/call/InAppCallControlsSlice4Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/ui/call/InAppCallControlsSlice4Test.ktnew file mode 100644index 0000000000..4db80df9fe--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/ui/call/InAppCallControlsSlice4Test.kt@@ -0,0 +1,219 @@+package com.vayunmathur.communicate.ui.call++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasContentDescriptionExactly+import androidx.compose.ui.test.hasText+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.CommunicateLine+import com.vayunmathur.communicate.data.call.CallCapabilities+import com.vayunmathur.communicate.data.call.InAppCallController+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.data.call.InAppCallState+import kotlin.test.BeforeTest+import kotlin.test.Test+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Slice-4 coverage for the shared call-screen controls (`ui/call/`).+ *+ * Robolectric + `createComposeRule`: renders the header, incoming actions,+ * capability-gated ongoing controls and the DTMF keypad, and asserts taps fan+ * out to the registry — the contract that keeps inert controls off screen.+ */+@RunWith(RobolectricTestRunner::class)+class InAppCallControlsSlice4Test {++    @get:Rule+    val rule = createComposeRule()++    private val actions = java.util.Collections.synchronizedList(mutableListOf<String>())++    private val controller = object : InAppCallController {+        override fun answer() { actions.add("answer") }+        override fun reject() { actions.add("reject") }+        override fun hangup() { actions.add("hangup") }+        override fun setMuted(muted: Boolean) { actions.add("muted=$muted") }+        override fun setSpeaker(on: Boolean) { actions.add("speaker=$on") }+    }++    @BeforeTest+    fun setUp() {+        ApplicationProvider.getApplicationContext<android.content.Cont

Diff truncated.