Modern Apps git

← Modern-Apps.git

communicate: visual voicemail tab with carrier and Google Voice

Commit
ffb5046dcafc92fbc5e74d3a883debbe4453b5f4
Author
Vayun Mathur <[email protected]>
When
2026-11-05 00:19 UTC (1 month ago)
Parents
bd884be
Fourth bottom-nav tab merging carrier VoicemailContract rows with Google
Voice folder-4 voicemails, newest first with per-line badges. Inline
ExoPlayer playback (session-cookie auth for GV media), carrier/GV
transcripts, lazy WRITE_CALL_LOG for carrier mark-read/delete, GV
mark-read via batchupdate and delete via archive. 14 new tests.

Diff

communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex 0d25bf18b2..ad331119b3 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -212,6 +212,10 @@ dependencies {     // Car-view store-listing screenshots render through the shared host renderer.     add("screenshotTestImplementation", project(":library:carhost")) +    // Voicemail tab audio playback: plain ExoPlayer (no session/controller stack —+    // voicemail clips are short local files, not a browsable media library).+    implementation(libs.androidx.media3.exoplayer)+     // voicemailNumber() reads TelephonyManager.voiceMailNumber, which the unit-test stub     // android.jar does not implement ("not mocked"). Robolectric supplies the framework     // shadows so the pilot lookup (and its permission/dual-SIM fallbacks) can be asserted
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex d432d4a12b..2cf97886e1 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -4,6 +4,8 @@     <uses-permission android:name="android.permission.READ_CONTACTS" />     <uses-permission android:name="android.permission.CALL_PHONE" />     <uses-permission android:name="android.permission.READ_CALL_LOG" />+    <!-- Voicemail tab mark-read/delete via the VoicemailContract provider. -->+    <uses-permission android:name="android.permission.WRITE_CALL_LOG" />     <uses-permission android:name="android.permission.READ_SMS" />     <uses-permission android:name="android.permission.RECEIVE_SMS" />     <uses-permission android:name="android.permission.RECEIVE_MMS" />
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex cc09eae974..8f2e63747f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -42,6 +42,7 @@ import com.vayunmathur.communicate.ui.CallLogsScreen import com.vayunmathur.communicate.ui.ConversationScreen import com.vayunmathur.communicate.ui.DialerScreen import com.vayunmathur.communicate.ui.MessagesScreen+import com.vayunmathur.communicate.ui.VoicemailScreen import com.vayunmathur.communicate.data.call.InAppCallPhase import com.vayunmathur.communicate.data.call.InAppCallRegistry import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallBridge@@ -383,7 +384,7 @@ private fun AppTelecomEffects(  @Composable private fun CommunicateTabs(backStack: NavBackStack<Route>) {-    val pagerState = rememberPagerState(pageCount = { 3 })+    val pagerState = rememberPagerState(pageCount = { 4 })     val tabs = listOf(         PagerTab(stringResource(R.string.messages_title), { IconSms() }) {             MessagesScreen(
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.ktindex e72c30d0ad..4dc6c1b032 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt@@ -75,6 +75,32 @@ data class CommunicateCallLogEntry(     val subscriptionId: Int? = null, ) +/**+ * One visual-voicemail row, either carrier ([android.provider.VoicemailContract])+ * or Google Voice (folder-4 listing). [contentUri] addresses the audio: a+ * provider row URI for carrier rows, the media URL for GV rows ([audioHeaders]+ * then carries the session cookies the endpoint requires). [transcript] is the+ * carrier transcription or the GV word-list join, when supplied.+ */+data class VoicemailEntry(+    val id: Long,+    val phoneNumber: String,+    val timestampMillis: Long,+    val durationSeconds: Long,+    val contentUri: String,+    val mimeType: String?,+    val hasAudio: Boolean,+    val transcript: String?,+    val isRead: Boolean,+    /** Physical SIM subscription id when the provider tags the row, null if unknown/GV. */+    val subscriptionId: Int? = null,+    val line: CommunicateLine = CommunicateLine.Sim,+    /** GV media auth (Cookie); empty for carrier rows. */+    val audioHeaders: Map<String, String> = emptyMap(),+    /** GV record id (`c.<opaque>`) for mark-read/delete; null for carrier rows. */+    val remoteId: String? = null,+)+ /**  * A media item attached to a message. SIM MMS parts arrive as local `content://`  * URIs; Google Voice media arrive as remote https URLs. [contentUri] holds whichever
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.ktindex 7e277007e0..c9dd374558 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryMerged.kt@@ -8,6 +8,7 @@ import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceClient import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession import com.vayunmathur.communicate.data.googlevoice.GvCall import com.vayunmathur.communicate.data.googlevoice.GvCallType+import com.vayunmathur.communicate.data.googlevoice.GvVoicemail import com.vayunmathur.communicate.data.googlevoice.GvMessage import com.vayunmathur.communicate.data.googlevoice.GvThread import com.vayunmathur.communicate.data.signal.SignalClient@@ -56,6 +57,61 @@ internal suspend fun CommunicateRepository.loadGoogleVoiceCalls(context: Context     }.getOrDefault(emptyList()) } +/** Google Voice voicemails (folder 4) for the Voicemail tab; empty when signed out. */+internal suspend fun CommunicateRepository.loadGoogleVoiceVoicemails(context: Context): List<VoicemailEntry> {+    val session = GoogleVoiceSession.get(context)+    if (!session.hasUsableCredentials()) return emptyList()+    return runCatching {+        val cookie = session.cookieHeader().orEmpty()+        val headers = if (cookie.isNotBlank()) mapOf("Cookie" to cookie) else emptyMap()+        GoogleVoiceClient.get(context).listVoicemails().map { it.toVoicemailEntry(context, headers) }+    }.getOrDefault(emptyList())+}++/** Voicemail tab contents: carrier rows plus GV rows, newest first. */+suspend fun CommunicateRepository.loadVoicemailsMerged(context: Context): List<VoicemailEntry> =+    withContext(Dispatchers.IO) {+        (loadCarrierVoicemails(context) + loadGoogleVoiceVoicemails(context))+            .sortedByDescending { it.timestampMillis }+    }++/** Mark a voicemail read, routing by line (provider write vs GV batchupdate). */+suspend fun CommunicateRepository.markVoicemailEntryRead(+    context: Context,+    entry: VoicemailEntry,+): Boolean = withContext(Dispatchers.IO) {+    when (entry.line) {+        CommunicateLine.GoogleVoice -> {+            val remoteId = entry.remoteId ?: return@withContext false+            runCatching {+                GoogleVoiceClient.get(context).markVoicemailRead(remoteId)+                true+            }.getOrDefault(false)+        }+        else -> markVoicemailRead(context, entry, read = true)+    }+}++/** Delete/archive a voicemail, routing by line (provider delete vs GV archive). */+suspend fun CommunicateRepository.deleteVoicemailEntry(+    context: Context,+    entry: VoicemailEntry,+): Boolean = withContext(Dispatchers.IO) {+    when (entry.line) {+        CommunicateLine.GoogleVoice -> {+            val remoteId = entry.remoteId ?: return@withContext false+            runCatching {+                GoogleVoiceClient.get(context).updateThreadAttributes(+                    remoteId,+                    com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser.ThreadAction.Archive,+                )+                true+            }.getOrDefault(false)+        }+        else -> deleteVoicemail(context, entry)+    }+}+ // ── Delete ( #542 ) ────────────────────────────────────────────────  /** Delete an entire conversation/thread, routing by [CommunicateLine]. */@@ -274,6 +330,23 @@ internal fun GvCall.toCallLogEntry(context: Context): CommunicateCallLogEntry =     line = CommunicateLine.GoogleVoice, ) +internal fun GvVoicemail.toVoicemailEntry(context: Context, audioHeaders: Map<String, String>): VoicemailEntry =+    VoicemailEntry(+        id = CommunicateRepository.stableThreadId(id),+        phoneNumber = phoneNumber,+        timestampMillis = timestampMillis,+        durationSeconds = durationSeconds,+        contentUri = audioUrl.orEmpty(),+        mimeType = "audio/mpeg",+        hasAudio = !audioUrl.isNullOrBlank(),+        transcript = transcript,+        isRead = read,+        subscriptionId = null,+        line = CommunicateLine.GoogleVoice,+        audioHeaders = audioHeaders,+        remoteId = id,+    )+ private fun GvCallType.toCommunicateCallType(): CommunicateCallType = when (this) {     GvCallType.Incoming -> CommunicateCallType.Incoming     GvCallType.Outgoing -> CommunicateCallType.Outgoing
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.ktindex 49751f713f..b90b10a318 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositorySim.kt@@ -1,12 +1,14 @@ package com.vayunmathur.communicate.data  import android.Manifest+import android.content.ContentValues import android.content.Context import android.content.Intent import android.net.Uri import android.provider.CallLog import android.provider.ContactsContract import android.provider.Telephony+import android.provider.VoicemailContract import android.telecom.TelecomManager import android.telephony.TelephonyManager import androidx.core.net.toUri@@ -457,6 +459,109 @@ fun CommunicateRepository.voicemailNumber(context: Context, choice: LineChoice?)     return runCatching { scoped.voiceMailNumber }.getOrNull()?.takeIf { it.isNotBlank() } } +/**+ * Carrier visual-voicemail inbox from [VoicemailContract], newest first.+ *+ * Read-only providers need only the default-dialer role (enforced by the+ * platform) plus READ_CALL_LOG — same gate as the call log. The audio itself+ * opens through each row's [VoicemailEntry.contentUri] data channel; the+ * carrier transcription rides along when the VVM client supplied one.+ */+fun CommunicateRepository.loadCarrierVoicemails(context: Context): List<VoicemailEntry> {+    if (!context.hasPermission(Manifest.permission.READ_CALL_LOG)) return emptyList()++    val projection = arrayOf(+        VoicemailContract.Voicemails._ID,+        VoicemailContract.Voicemails.NUMBER,+        VoicemailContract.Voicemails.DATE,+        VoicemailContract.Voicemails.DURATION,+        VoicemailContract.Voicemails.HAS_CONTENT,+        VoicemailContract.Voicemails.MIME_TYPE,+        VoicemailContract.Voicemails.TRANSCRIPTION,+        VoicemailContract.Voicemails.IS_READ,+        VoicemailContract.Voicemails.PHONE_ACCOUNT_ID,+    )+    return runCatching {+        context.contentResolver.query(+            VoicemailContract.Voicemails.CONTENT_URI,+            projection,+            null,+            null,+            "${VoicemailContract.Voicemails.DATE} DESC",+        )?.use { cursor ->+            buildList {+                val id = cursor.getColumnIndexOrThrow(VoicemailContract.Voicemails._ID)+                val number = cursor.getColumnIndexOrThrow(VoicemailContract.Voicemails.NUMBER)+                val date = cursor.getColumnIndexOrThrow(VoicemailContract.Voicemails.DATE)+                val duration = cursor.getColumnIndexOrThrow(VoicemailContract.Voicemails.DURATION)+                val hasContent = cursor.getColumnIndex(VoicemailContract.Voicemails.HAS_CONTENT)+                val mimeType = cursor.getColumnIndex(VoicemailContract.Voicemails.MIME_TYPE)+                val transcription = cursor.getColumnIndex(VoicemailContract.Voicemails.TRANSCRIPTION)+                val isRead = cursor.getColumnIndexOrThrow(VoicemailContract.Voicemails.IS_READ)+                val account = cursor.getColumnIndex(VoicemailContract.Voicemails.PHONE_ACCOUNT_ID)+                val activeSubs = SimManager.activeSims(context).map { it.subscriptionId }.toSet()++                while (cursor.moveToNext()) {+                    val rowId = cursor.getLong(id)+                    // PHONE_ACCOUNT_ID tagging mirrors the call log: keep it only when it+                    // maps to an active SIM so the row can be labeled by SIM.+                    val subId = account.takeIf { it >= 0 }+                        ?.let { cursor.getString(it) }+                        ?.toIntOrNull()+                        ?.takeIf { it in activeSubs }+                    add(+                        VoicemailEntry(+                            id = rowId,+                            phoneNumber = cursor.getString(number).orEmpty().ifBlank { "Unknown" },+                            timestampMillis = cursor.getLong(date),+                            durationSeconds = cursor.getLong(duration),+                            contentUri = Uri.withAppendedPath(+                                VoicemailContract.Voicemails.CONTENT_URI,+                                rowId.toString(),+                            ).toString(),+                            mimeType = mimeType.takeIf { it >= 0 }?.let { cursor.getString(it) },+                            hasAudio = hasContent.takeIf { it >= 0 }+                                ?.let { cursor.getInt(it) != 0 } ?: false,+                            transcript = transcription.takeIf { it >= 0 }+                                ?.let { cursor.getString(it)?.takeIf { it.isNotBlank() } },+                            isRead = cursor.getInt(isRead) != 0,+                            subscriptionId = subId,+                        )+                    )+                }+            }+        }.orEmpty()+    }.getOrDefault(emptyList())+}++/** Mark a carrier voicemail read/unread. Needs WRITE_CALL_LOG. */+fun CommunicateRepository.markVoicemailRead(+    context: Context,+    voicemail: VoicemailEntry,+    read: Boolean,+): Boolean {+    if (!context.hasPermission(Manifest.permission.WRITE_CALL_LOG)) return false+    val values = ContentValues().apply {+        put(VoicemailContract.Voicemails.IS_READ, if (read) 1 else 0)+    }+    return runCatching {+        context.contentResolver.update(+            Uri.parse(voicemail.contentUri),+            values,+            null,+            null,+        ) > 0+    }.getOrDefault(false)+}++/** Delete a carrier voicemail. Needs WRITE_CALL_LOG. */+fun CommunicateRepository.deleteVoicemail(context: Context, voicemail: VoicemailEntry): Boolean {+    if (!context.hasPermission(Manifest.permission.WRITE_CALL_LOG)) return false+    return runCatching {+        context.contentResolver.delete(Uri.parse(voicemail.contentUri), null, null) >= 0+    }.getOrDefault(false)+}+ fun CommunicateRepository.getOrCreateSmsThreadId(context: Context, address: String): Long? = runCatching {     Telephony.Threads.getOrCreateThreadId(context, address) }.getOrNull()
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.ktindex b284ffc5f1..43faf5205b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceClient.kt@@ -57,6 +57,17 @@ class GoogleVoiceClient(private val session: GoogleVoiceSession) {         return GoogleVoiceParser.parseCalls(body)     } +    /** Carrier-style inbox for the Voicemail tab: folder 4 holds `c.`-records with transcripts + media. */+    suspend fun listVoicemails(): List<GvVoicemail> {+        val body = post("api2thread/list", GoogleVoiceParser.buildListBody(GvFolder.Voicemail))+        return GoogleVoiceParser.parseVoicemails(body)+    }++    /** Mark a voicemail played/read — same batchupdate shape the web app sends on playback. */+    suspend fun markVoicemailRead(remoteId: String) {+        updateThreadAttributes(remoteId, GoogleVoiceParser.ThreadAction.MarkRead)+    }+     suspend fun sendSms(recipient: String, text: String, threadRemoteId: String? = null) {         post("api2thread/sendsms", GoogleVoiceParser.buildSendSmsBody(recipient, text, threadRemoteId))     }
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceMedia.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceMedia.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceMedia.ktindex 822d94c503..da3c04d3dc 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceMedia.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceMedia.kt@@ -86,6 +86,22 @@ internal fun looksLikeMediaUrl(raw: String): Boolean { internal fun recordId(record: JsonArray): String? =     (record.firstOrNull() as? JsonPrimitive)?.takeIf { it.isString }?.content +/**+ * Carrier transcription for a folder-4 voicemail item: slot 6 holds+ * `[overallConfidence, [[word, null, null, wordConfidence], ...]]`, or null+ * when the message hasn't been transcribed yet. Words join with single spaces.+ */+internal fun JsonArray.transcriptText(): String? {+    val block = getOrNull(GoogleVoiceParser.ITEM_TRANSCRIPT) as? JsonArray ?: return null+    val words = block.getOrNull(1) as? JsonArray ?: return null+    return words.mapNotNull { (it as? JsonArray)?.getOrNull(0) as? JsonPrimitive }+        .filter { it.isString }+        .map { it.content }+        .filter { it.isNotBlank() }+        .joinToString(" ")+        .takeIf { it.isNotBlank() }+}+ internal fun JsonArray.strAt(i: Int): String? =     (getOrNull(i) as? JsonPrimitive)?.takeIf { it.isString }?.content 
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.ktindex 1881313aff..1f57aeb2af 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceModels.kt@@ -62,6 +62,23 @@ data class GvCall(     val durationSeconds: Long, ) +/**+ * One Google Voice voicemail from a folder-4 `api2thread/list` record.+ * [transcript] joins the word list at item slot 6 (null when the carrier+ * hasn't transcribed it yet); [audioUrl] is the item-slot-11 media URL;+ * [read] is the item-slot-13 flag (1 vs 8 in captures — treated as read+ * unless 8, verified against mark-read round-trips).+ */+data class GvVoicemail(+    val id: String,+    val phoneNumber: String,+    val timestampMillis: Long,+    val durationSeconds: Long,+    val transcript: String?,+    val audioUrl: String?,+    val read: Boolean,+)+ /** SIP registration material from `sipregisterinfo/get`, consumed by the calling layer. */ data class GvSipRegisterInfo(     val phoneNumber: String?,
communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.ktindex 38b901e76c..d289212b6f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/googlevoice/GoogleVoiceParser.kt@@ -114,6 +114,32 @@ object GoogleVoiceParser {         }.distinctBy { it.id }     } +    /**+     * Voicemails from a folder-4 `api2thread/list` body. Records are `c.`-keyed+     * like calls, but the item carries the voicemail marker ([ITEM_VM_TYPE] = 2,+     * calls use 14), the transcript word list ([ITEM_TRANSCRIPT]), and the+     * playable media URL ([ITEM_AUDIO_URL]).+     */+    fun parseVoicemails(body: String): List<GvVoicemail> {+        val root = parseOrNull(body) ?: return emptyList()+        return findRecords(root, prefixes = listOf("c.")).mapNotNull { record ->+            val id = recordId(record) ?: return@mapNotNull null+            val items = record.arrAt(ITEMS)?.mapNotNull { it as? JsonArray }.orEmpty()+            val newest = items.firstOrNull() ?: return@mapNotNull null+            if (newest.longAt(ITEM_VM_TYPE) != VM_TYPE_VOICEMAIL) return@mapNotNull null+            val counterparty = counterpartyOf(record, newest) ?: return@mapNotNull null+            GvVoicemail(+                id = id,+                phoneNumber = counterparty,+                timestampMillis = newest.longAt(ITEM_TS)?.let { normalizeTimestampMillis(it) } ?: 0L,+                durationSeconds = newest.longAt(ITEM_DURATION) ?: 0L,+                transcript = newest.transcriptText(),+                audioUrl = newest.strAt(ITEM_AUDIO_URL)?.takeIf { it.isNotBlank() },+                read = newest.longAt(ITEM_VM_READ) != VM_READ_UNREAD,+            )+        }.distinctBy { it.id }+    }+     fun parseSipRegisterInfo(body: String): GvSipRegisterInfo {         val root = parseOrNull(body) ?: return GvSipRegisterInfo(null, emptyList())         val phone = firstPhone(root)@@ -141,6 +167,19 @@ object GoogleVoiceParser {     internal const val ITEM_BODY = 9     internal const val ITEM_COUNTERPARTY = 15     internal const val ITEM_MEDIA_FLAG = 16+    /**+     * Folder-4 voicemail item slots (live capture): [ITEM_VM_TYPE] = 2 marks a+     * voicemail (regular calls carry 14); [ITEM_TRANSCRIPT] holds+     * `[confidence, [[word, null, null, wordConfidence], ...]]` or null when+     * untranscribed; [ITEM_AUDIO_URL] is the playable media URL;+     * [ITEM_VM_READ] reads 1 once played, [VM_READ_UNREAD] (8) before.+     */+    internal const val ITEM_VM_TYPE = 4+    internal const val ITEM_TRANSCRIPT = 6+    internal const val ITEM_AUDIO_URL = 11+    internal const val ITEM_VM_READ = 13+    internal const val VM_TYPE_VOICEMAIL = 2L+    internal const val VM_READ_UNREAD = 8L     internal const val RECORD_FALLBACK_A = 4     internal const val RECORD_FALLBACK_B = 7     internal const val E164_LENGTH = 10
communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailContent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailContent.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailContent.ktnew file mode 100644index 0000000000..3409f64316--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailContent.kt@@ -0,0 +1,162 @@+package com.vayunmathur.communicate.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.VoicemailEntry+import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconVoicemail+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OverflowMenu+import com.vayunmathur.library.ui.Text++/**+ * Voicemail inbox list, stateless: rows plus the delete-confirm dialog. Split+ * out so screenshot previews can render entries without the provider, the+ * permission gates, or the player above — same split as [CallLogsContent].+ *+ * [expandedId] is hoisted so only one row's player is composed at a time.+ * [onToggleExpand] also serves as the mark-read hook: opening a row marks it.+ * [onPlayed] fires when audio starts, so playback also marks the row read+ * (covers rows opened while already read-flagged stale).+ */+@Composable+fun VoicemailContent(+    entries: List<VoicemailEntry>,+    expandedId: Long?,+    onToggleExpand: (VoicemailEntry) -> Unit,+    onDelete: (VoicemailEntry) -> Unit,+    onPlayed: (VoicemailEntry) -> Unit = {},+    modifier: Modifier = Modifier,+) {+    var pendingDelete by remember { mutableStateOf<VoicemailEntry?>(null) }+    LazyColumn(+        modifier = modifier.fillMaxSize(),+        contentPadding = PaddingValues(vertical = 8.dp),+    ) {+        items(entries, key = { it.id }) { entry ->+            VoicemailRow(+                entry = entry,+                expanded = entry.id == expandedId,+                onToggleExpand = { onToggleExpand(entry) },+                onDelete = { pendingDelete = entry },+                onPlayed = { onPlayed(entry) },+            )+        }+    }+    val toDelete = pendingDelete+    if (toDelete != null) {+        ConfirmDialog(+            title = stringResource(R.string.delete_voicemail_title),+            message = stringResource(R.string.delete_voicemail_message),+            confirmLabel = stringResource(com.vayunmathur.library.ui.R.string.delete),+            dismissLabel = stringResource(com.vayunmathur.library.ui.R.string.cancel),+            destructive = true,+            onConfirm = {+                pendingDelete = null+                onDelete(toDelete)+            },+            onDismiss = { pendingDelete = null },+        )+    }+}++@Composable+private fun VoicemailRow(+    entry: VoicemailEntry,+    expanded: Boolean,+    onToggleExpand: () -> Unit,+    onDelete: () -> Unit,+    onPlayed: () -> Unit,+) {+    ListItem(+        content = {+            Row(verticalAlignment = Alignment.CenterVertically) {+                Text(+                    entry.phoneNumber,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                    fontWeight = if (entry.isRead) FontWeight.Medium else FontWeight.Bold,+                )+                LineBadge(entry.line, entry.subscriptionId, modifier = Modifier.padding(start = 6.dp))+            }+        },+        supportingContent = {+            Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+                Text(+                    "${formatDateTime(LocalContext.current, entry.timestampMillis)} · " ++                        stringResource(R.string.voicemail_duration, entry.durationSeconds),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                )+                if (expanded && entry.transcript != null) {+                    Text(+                        entry.transcript,+                        style = MaterialTheme.typography.bodyMedium,+                        maxLines = 4,+                        overflow = TextOverflow.Ellipsis,+                        modifier = Modifier.padding(top = 4.dp),+                    )+                }+            }+        },+        leadingContent = { IconVoicemail() },+        trailingContent = {+            OverflowMenu(icon = { IconMoreVert() }) {+                Item(+                    text = stringResource(com.vayunmathur.library.ui.R.string.delete),+                    leadingIcon = { IconDelete() },+                    onClick = onDelete,+                )+            }+        },+        colors = ListItemDefaults.colors(containerColor = Color.Transparent),+        modifier = Modifier.clickable(onClick = onToggleExpand),+    )+    if (expanded) {+        if (entry.hasAudio) {+            VoicemailPlayer(+                audioUri = entry.contentUri,+                onPlayed = {},+                modifier = Modifier+                    .fillMaxWidth()+                    .padding(start = 56.dp, end = 16.dp, bottom = 8.dp),+            )+        } else {+            Text(+                stringResource(R.string.voicemail_no_audio),+                style = MaterialTheme.typography.labelMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                modifier = Modifier.padding(start = 56.dp, end = 16.dp, bottom = 8.dp),+            )+        }+    }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailPlayer.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailPlayer.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailPlayer.ktnew file mode 100644index 0000000000..155b3058c5--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailPlayer.kt@@ -0,0 +1,161 @@+package com.vayunmathur.communicate.ui++import android.net.Uri+import androidx.annotation.OptIn+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.media3.common.MediaItem+import androidx.media3.common.Player+import androidx.media3.common.util.UnstableApi+import androidx.media3.exoplayer.ExoPlayer+import com.vayunmathur.communicate.R+import com.vayunmathur.library.ui.FilledIconButton+import com.vayunmathur.library.ui.IconPause+import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Slider+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive++/**+ * Inline audio player for one voicemail row: play/pause plus a scrub slider+ * with elapsed/total labels.+ *+ * A plain [ExoPlayer] (not the session/controller stack music uses) — voicemail+ * clips are short files, not a browsable library. The player is created+ * per expanded row and released when the row leaves composition. [onPlayed]+ * fires once playback starts, so the caller can mark the row read.+ * [requestHeaders] carries auth (GV media needs the session Cookie); empty+ * for carrier rows, whose provider URIs need none.+ */+@OptIn(UnstableApi::class)+@Composable+fun VoicemailPlayer(+    audioUri: String,+    onPlayed: () -> Unit,+    modifier: Modifier = Modifier,+    requestHeaders: Map<String, String> = emptyMap(),+) {+    val context = LocalContext.current+    val playFailed = stringResource(R.string.voicemail_play_failed)+    var failed by remember { mutableStateOf(false) }+    var playing by remember { mutableStateOf(false) }+    var durationMs by remember { mutableLongStateOf(0L) }+    var positionMs by remember { mutableLongStateOf(0L) }+    var scrubTo by remember { mutableFloatStateOf(-1f) }+    var notified by remember { mutableStateOf(false) }++    val player = remember(audioUri) {+        ExoPlayer.Builder(context).build().apply {+            setMediaItem(MediaItem.fromUri(Uri.parse(audioUri)))+            addListener(object : Player.Listener {+                override fun onIsPlayingChanged(isPlaying: Boolean) {+                    playing = isPlaying+                }++                override fun onPlaybackStateChanged(state: Int) {+                    if (state == Player.STATE_READY) {+                        durationMs = duration.coerceAtLeast(0L)+                    }+                    if (state == Player.STATE_ENDED) {+                        playing = false+                    }+                }++                override fun onPlayerError(error: androidx.media3.common.PlaybackException) {+                    failed = true+                }+            })+            prepare()+        }+    }+    DisposableEffect(player) {+        onDispose { player.release() }+    }+    LaunchedEffect(failed) {+        if (failed) AppMessages.show(playFailed)+    }+    LaunchedEffect(playing) {+        while (isActive && playing) {+            positionMs = player.currentPosition+            delay(250)+        }+        positionMs = player.currentPosition+    }+    LaunchedEffect(playing, notified, onPlayed) {+        if (playing && !notified) {+            notified = true+            onPlayed()+        }+    }++    val shownPosition = (scrubTo.takeIf { it >= 0f }?.toLong() ?: positionMs).coerceIn(0L, durationMs)+    Column(modifier = modifier.fillMaxWidth()) {+        Row(+            modifier = Modifier.fillMaxWidth(),+            verticalAlignment = Alignment.CenterVertically,+            horizontalArrangement = Arrangement.spacedBy(8.dp),+        ) {+            FilledIconButton(+                onClick = {+                    if (failed) return@FilledIconButton+                    if (player.isPlaying) player.pause() else player.play()+                },+                enabled = !failed,+                modifier = Modifier.size(44.dp),+            ) {+                if (playing) IconPause() else IconPlay()+            }+            Text(+                formatClipTime(shownPosition),+                style = MaterialTheme.typography.labelMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+            Slider(+                value = if (durationMs > 0) shownPosition.toFloat() / durationMs else 0f,+                onValueChange = { scrubTo = it * durationMs },+                onValueChangeFinished = {+                    val target = scrubTo+                    scrubTo = -1f+                    if (target >= 0f) {+                        player.seekTo(target.toLong().coerceIn(0L, durationMs))+                        positionMs = player.currentPosition+                    }+                },+                enabled = !failed && durationMs > 0,+                modifier = Modifier.weight(1f),+            )+            Text(+                formatClipTime(durationMs),+                style = MaterialTheme.typography.labelMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+    }+}++/** mm:ss for the player labels; the row itself uses the `voicemail_duration` string. */+private fun formatClipTime(millis: Long): String {+    val totalSeconds = (millis / 1000).coerceAtLeast(0L)+    return "%d:%02d".format(totalSeconds / 60, totalSeconds % 60)+}
communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailScreen.ktnew file mode 100644index 0000000000..38e8d2b46b--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/VoicemailScreen.kt@@ -0,0 +1,164 @@+package com.vayunmathur.communicate.ui++import android.Manifest+import android.content.pm.PackageManager+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.core.content.ContextCompat+import com.vayunmathur.communicate.R+import com.vayunmathur.communicate.data.VoicemailEntry+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.deleteVoicemailEntry+import com.vayunmathur.communicate.data.loadVoicemailsMerged+import com.vayunmathur.communicate.data.markVoicemailEntryRead+import com.vayunmathur.communicate.data.markVoicemailRead+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.IconVoicemail+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberPermissionRequest+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Carrier visual-voicemail inbox tab.+ *+ * Same slice as [CallLogsScreen]: [AppScaffold] + [DefaultDialerGate] (the+ * provider enforces default-dialer for reads) + [PermissionGate] on+ * READ_CALL_LOG + [produceState] loader + stateless [VoicemailContent].+ *+ * WRITE_CALL_LOG is requested lazily — only when the user expands a row+ * (mark-read) or deletes — so the tab stays fully usable read-only without it.+ * Google Voice voicemails join this list in Phase 2; until then the tab is+ * carrier rows only.+ */+@Composable+fun VoicemailScreen() {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    var tick by remember { mutableStateOf(0) }+    var expandedId by remember { mutableLongStateOf(-1L) }+    // #735 (same as MessagesScreen): PermissionGate reads checkSelfPermission+    // during composition with no resume trigger, so granting from Settings+    // never recomposes the gate. resumeRevision forces a re-check + reload.+    val resumeRevision = rememberResumeRevision()+    val markReadFailed = stringResource(R.string.voicemail_mark_read_failed)+    val writeNeeded = stringResource(R.string.permission_write_call_log_message)++    val requestWrite = rememberPermissionRequest(Manifest.permission.WRITE_CALL_LOG) {}+    fun hasWrite(): Boolean = ContextCompat.checkSelfPermission(+        context,+        Manifest.permission.WRITE_CALL_LOG,+    ) == PackageManager.PERMISSION_GRANTED++    fun markRead(entry: VoicemailEntry) {+        if (entry.isRead) return+        if (!hasWrite()) {+            AppMessages.show(writeNeeded)+            requestWrite()+            return+        }+        scope.launch {+            val ok = withContext(Dispatchers.IO) {+                CommunicateRepository.markVoicemailRead(context, entry, read = true)+            }+            if (ok) tick++ else AppMessages.show(markReadFailed)+        }+    }++    AppScaffold(+        title = stringResource(R.string.voicemail_title),+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        DefaultDialerGate(modifier = Modifier.padding(padding)) { roleRevision ->+            PermissionGate(+                permission = Manifest.permission.READ_CALL_LOG,+                message = stringResource(R.string.permission_voicemail_message),+                modifier = Modifier.padding(padding),+            ) { permissionRevision ->+                val voicemails = produceState<List<VoicemailEntry>?>(+                    initialValue = null,+                    roleRevision,+                    permissionRevision,+                    resumeRevision,+                    tick,+                ) {+                    value = CommunicateRepository.loadVoicemailsMerged(context)+                }+                when (val rows = voicemails.value) {+                    null -> com.vayunmathur.library.ui.LoadingState(Modifier.padding(padding))+                    emptyList<VoicemailEntry>() -> EmptyState(+                        title = stringResource(R.string.empty_voicemails),+                        message = stringResource(R.string.empty_voicemails_setup),+                        icon = { IconVoicemail() },+                        modifier = Modifier.padding(padding),+                    )+                    else -> {+                        VoicemailContent(+                            entries = rows,+                            expandedId = expandedId.takeIf { it >= 0 },+                            onToggleExpand = { entry ->+                                expandedId = if (expandedId == entry.id) -1L else entry.id+                                if (expandedId >= 0) markRead(entry)+                            },+                            onPlayed = ::markRead,+                            onDelete = { toDelete ->+                                // GV rows archive through the GV API — no call-log write needed.+                                if (toDelete.line == CommunicateLine.GoogleVoice) {+                                    scope.launch {+                                        val ok = CommunicateRepository.deleteVoicemailEntry(+                                            context,+                                            toDelete,+                                        )+                                        if (ok) {+                                            if (expandedId == toDelete.id) expandedId = -1L+                                            tick+++                                        } else {+                                            AppMessages.show(+                                                context.getString(R.string.delete_failed),+                                            )+                                        }+                                    }+                                } else if (!hasWrite()) {+                                    AppMessages.show(writeNeeded)+                                    requestWrite()+                                } else {+                                    scope.launch {+                                        val ok = withContext(Dispatchers.IO) {+                                            CommunicateRepository.deleteVoicemailEntry(+                                                context,+                                                toDelete,+                                            )+                                        }+                                        if (ok) {+                                            if (expandedId == toDelete.id) expandedId = -1L+                                            tick+++                                        } else {+                                            AppMessages.show(+                                                context.getString(R.string.delete_failed),+                                            )+                                        }+                                    }+                                }+                            },+                            modifier = Modifier.padding(padding),+                        )+                    }+                }+            }+        }+    }+}
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex 520b460ab2..56efedef9f 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -4,6 +4,7 @@     <string name="messages_title">Messages</string>     <string name="dialer_title">Dialer</string>     <string name="call_logs_title">Call logs</string>+    <string name="voicemail_title">Voicemail</string>     <string name="conversation_title">Conversation</string>     <string name="permission_title">Permission needed</string>     <string name="default_app_title">Default app needed</string>@@ -21,6 +22,18 @@     <string name="empty_contacts">No contacts found</string>     <string name="empty_contacts_for_digits">No contacts match those keys</string>     <string name="empty_call_logs">No recent calls found</string>+    <string name="empty_voicemails">No voicemails yet</string>+    <string name="empty_voicemails_setup">Your carrier hasn\'t delivered any visual voicemails here yet. If your carrier supports it, they\'ll appear here automatically.</string>+    <!-- %1$d = seconds; voicemail row duration, e.g. "42 sec". -->+    <string name="voicemail_duration">%1$d sec</string>+    <string name="voicemail_transcript_title">Transcript</string>+    <string name="voicemail_no_audio">No audio attached to this voicemail</string>+    <string name="voicemail_play_failed">Couldn\'t play this voicemail</string>+    <string name="voicemail_mark_read_failed">Couldn\'t update this voicemail</string>+    <string name="delete_voicemail_title">Delete voicemail?</string>+    <string name="delete_voicemail_message">This will remove this voicemail from your inbox.</string>+    <string name="permission_voicemail_message">Allow Call log access to show your visual voicemails.</string>+    <string name="permission_write_call_log_message">Allow call-log write access to mark voicemails read and delete them.</string>     <string name="new_message">New message</string>     <string name="compose_message">Compose message</string>     <string name="phone_number">Phone number</string>
communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.kt
diff --git a/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.kt b/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.ktindex c632e8e63b..3b5c8971bb 100644--- a/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.kt+++ b/communicate/src/screenshotTest/kotlin/com/vayunmathur/communicate/ui/MetadataPreviews.kt@@ -15,6 +15,7 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconCall import com.vayunmathur.library.ui.IconHistory import com.vayunmathur.library.ui.IconSms+import com.vayunmathur.library.ui.IconVoicemail import com.vayunmathur.library.ui.PagerTab import com.vayunmathur.library.ui.TabStyle import com.vayunmathur.library.ui.TabbedPagerScaffold@@ -26,7 +27,7 @@ private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"  * Store listing images for `:communicate` phone tabs, rendered from Compose previews.  *  * The car shots live in CarMetadataPreviews (head-unit UI, no phone chrome). These- * cover the handset tabs: Messages, Dialer, Call logs. The tab screens were split+ * cover the handset tabs: Messages, Dialer, Call logs, Voicemail. The tab screens were split  * into stateless `*Content` slices so previews render without the SMS provider,  * the SIM/session lines, or the contact/call-log content providers.  */@@ -95,6 +96,42 @@ class MetadataPreviews {         ),     ) +    private val voicemails = listOf(+        VoicemailEntry(+            id = 1,+            phoneNumber = "+14155550102",+            timestampMillis = 1_785_566_000_000,+            durationSeconds = 42,+            contentUri = "content://com.android.voicemail/voicemail/1",+            mimeType = "audio/amr",+            hasAudio = true,+            transcript = null,+            isRead = false,+        ),+        VoicemailEntry(+            id = 2,+            phoneNumber = "+14155550109",+            timestampMillis = 1_785_560_000_000,+            durationSeconds = 18,+            contentUri = "content://com.android.voicemail/voicemail/2",+            mimeType = "audio/amr",+            hasAudio = true,+            transcript = "Hey, it\'s Maya — call me back when you get this, it\'s about Thursday.",+            isRead = true,+        ),+        VoicemailEntry(+            id = 3,+            phoneNumber = "Unknown",+            timestampMillis = 1_785_550_000_000,+            durationSeconds = 0,+            contentUri = "content://com.android.voicemail/voicemail/3",+            mimeType = null,+            hasAudio = false,+            transcript = null,+            isRead = true,+        ),+    )+     @PreviewTest     @Preview(name = "1-messages", device = PHONE, group = "phone", showSystemUi = true)     @Composable@@ -116,6 +153,13 @@ class MetadataPreviews {         ChromePreview(selectedTab = 2)     } +    @PreviewTest+    @Preview(name = "4-voicemail", device = PHONE, group = "phone", showSystemUi = true)+    @Composable+    fun Preview4Voicemail() {+        ChromePreview(selectedTab = 3)+    }+     @Composable     private fun MessagesContent() {         MessagesListContent(@@ -142,10 +186,20 @@ class MetadataPreviews {         )     } +    @Composable+    private fun VoicemailContentTab() {+        VoicemailContent(+            entries = voicemails,+            expandedId = 2L,+            onToggleExpand = {},+            onDelete = {},+        )+    }+     /**      * The app's real tab chrome around preview screen content: the same-     * [TabbedPagerScaffold] with the same Messages/Dialer/Call-logs tabs-     * `CommunicateTabs` declares. Only the selected tab is literal.+     * [TabbedPagerScaffold] with the same Messages/Dialer/Call-logs/Voicemail+     * tabs `CommunicateTabs` declares. Only the selected tab is literal.      */     @Composable     private fun ChromePreview(selectedTab: Int) {@@ -154,6 +208,7 @@ class MetadataPreviews {                 PagerTab("Messages", { IconSms() }) { MessagesContent() },                 PagerTab("Dialer", { IconCall() }) { DialerContentTab() },                 PagerTab("Call logs", { IconHistory() }) { CallLogsContentTab() },+                PagerTab("Voicemail", { IconVoicemail() }) { VoicemailContentTab() },             )             TabbedPagerScaffold(                 tabs = tabs,
communicate/src/test/java/com/vayunmathur/communicate/data/CarrierVoicemailTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/CarrierVoicemailTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/CarrierVoicemailTest.ktnew file mode 100644index 0000000000..d86f09cc3a--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/CarrierVoicemailTest.kt@@ -0,0 +1,214 @@+package com.vayunmathur.communicate.data++import android.Manifest+import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.provider.VoicemailContract+import androidx.test.core.app.ApplicationProvider+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.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * Carrier visual-voicemail provider reads ([android.provider.VoicemailContract]).+ *+ * The stub android.jar answers `ContentResolver.query` with "not mocked", so a+ * fake provider serves the rows as [MatrixCursor]s. (Robolectric 4.17's+ * `ShadowContentResolver.setCursor(Uri, …)` only accepts the stub+ * `BaseCursor`, whose accessors all throw — a provider is the data-bearing+ * path.)+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class VoicemailEntryTest {++    class FakeVoicemailProvider : ContentProvider() {+        var rows: List<Array<Any?>> = emptyList()+        var updateResult: Int = 0+        var deleteResult: Int = 0++        private val columns = arrayOf(+            VoicemailContract.Voicemails._ID,+            VoicemailContract.Voicemails.NUMBER,+            VoicemailContract.Voicemails.DATE,+            VoicemailContract.Voicemails.DURATION,+            VoicemailContract.Voicemails.HAS_CONTENT,+            VoicemailContract.Voicemails.MIME_TYPE,+            VoicemailContract.Voicemails.TRANSCRIPTION,+            VoicemailContract.Voicemails.IS_READ,+            VoicemailContract.Voicemails.PHONE_ACCOUNT_ID,+        )++        override fun onCreate(): Boolean = true++        override fun query(+            uri: Uri,+            projection: Array<String>?,+            selection: String?,+            selectionArgs: Array<String>?,+            sortOrder: String?,+        ): Cursor {+            val cursor = MatrixCursor(columns, rows.size)+            rows.forEach { cursor.addRow(it) }+            return cursor+        }++        override fun getType(uri: Uri): String? = null++        override fun insert(uri: Uri, values: ContentValues?): Uri? = null++        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int =+            deleteResult++        override fun update(+            uri: Uri,+            values: ContentValues?,+            selection: String?,+            selectionArgs: Array<String>?,+        ): Int = updateResult+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private lateinit var provider: FakeVoicemailProvider++    private fun setUp(rows: List<Array<Any?>> = emptyList(), grantWrite: Boolean = true) {+        provider = Robolectric.setupContentProvider(+            FakeVoicemailProvider::class.java,+            VoicemailContract.AUTHORITY,+        )+        provider.rows = rows+        shadowOf(context as Application).grantPermissions(Manifest.permission.READ_CALL_LOG)+        if (grantWrite) {+            shadowOf(context as Application).grantPermissions(Manifest.permission.WRITE_CALL_LOG)+        }+    }++    private fun row(+        id: Long = 1L,+        number: String? = "+14155550102",+        date: Long = 1_785_566_000_000L,+        duration: Long = 42L,+        hasContent: Int = 1,+        mimeType: String? = "audio/amr",+        transcription: String? = null,+        isRead: Int = 0,+        account: String? = null,+    ): Array<Any?> =+        arrayOf(id, number, date, duration, hasContent, mimeType, transcription, isRead, account)++    private fun entry(id: Long = 7L, read: Boolean = false) = VoicemailEntry(+        id = id,+        phoneNumber = "+14155550102",+        timestampMillis = 0,+        durationSeconds = 10,+        contentUri = Uri.withAppendedPath(+            VoicemailContract.Voicemails.CONTENT_URI,+            id.toString(),+        ).toString(),+        mimeType = "audio/amr",+        hasAudio = true,+        transcript = null,+        isRead = read,+    )++    @Test+    fun `maps provider row to model`() {+        setUp(listOf(row(transcription = "Call me back", isRead = 0)))++        val rows = CommunicateRepository.loadCarrierVoicemails(context)++        assertEquals(1, rows.size)+        val loaded = rows.single()+        assertEquals(1L, loaded.id)+        assertEquals("+14155550102", loaded.phoneNumber)+        assertEquals(1_785_566_000_000L, loaded.timestampMillis)+        assertEquals(42L, loaded.durationSeconds)+        assertEquals(+            Uri.withAppendedPath(VoicemailContract.Voicemails.CONTENT_URI, "1").toString(),+            loaded.contentUri,+        )+        assertEquals("audio/amr", loaded.mimeType)+        assertTrue(loaded.hasAudio)+        assertEquals("Call me back", loaded.transcript)+        assertFalse(loaded.isRead)+        assertNull(loaded.subscriptionId)+        assertEquals(CommunicateLine.Sim, loaded.line)+    }++    @Test+    fun `blank number falls back to Unknown and blank transcript to null`() {+        setUp(listOf(row(number = "  ", transcription = "  ", hasContent = 0)))++        val loaded = CommunicateRepository.loadCarrierVoicemails(context).single()++        assertEquals("Unknown", loaded.phoneNumber)+        assertNull(loaded.transcript)+        assertFalse(loaded.hasAudio)+    }++    @Test+    fun `returns empty without read permission`() {+        setUp(listOf(row()))+        shadowOf(context as Application).denyPermissions(Manifest.permission.READ_CALL_LOG)++        assertTrue(CommunicateRepository.loadCarrierVoicemails(context).isEmpty())+    }++    @Test+    fun `returns empty when provider has no rows`() {+        setUp()++        assertTrue(CommunicateRepository.loadCarrierVoicemails(context).isEmpty())+    }++    @Test+    fun `mark read updates provider and returns true`() {+        setUp()+        provider.updateResult = 1++        assertTrue(CommunicateRepository.markVoicemailRead(context, entry(), read = true))+    }++    @Test+    fun `mark read returns false without write permission`() {+        setUp(grantWrite = false)++        assertFalse(CommunicateRepository.markVoicemailRead(context, entry(), read = true))+    }++    @Test+    fun `mark read returns false when provider updates nothing`() {+        setUp()+        provider.updateResult = 0++        assertFalse(CommunicateRepository.markVoicemailRead(context, entry(), read = true))+    }++    @Test+    fun `delete removes row and returns true`() {+        setUp()+        provider.deleteResult = 1++        assertTrue(CommunicateRepository.deleteVoicemail(context, entry()))+    }++    @Test+    fun `delete returns false without write permission`() {+        setUp(grantWrite = false)++        assertFalse(CommunicateRepository.deleteVoicemail(context, entry()))+    }+}
communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.ktindex 7463c34ec0..1c3eb48c68 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/googlevoice/GoogleVoiceParserTest.kt@@ -214,4 +214,64 @@ class GoogleVoiceParserTest {         val body = "[\"+15550001111\",null,[\"settings\"]]"         assertEquals("+15550001111", GoogleVoiceParser.parseAccount(body).phoneNumber)     }++    // Voicemail records (folder 4): type slot 2 marks voicemail (calls use 14);+    // transcript word list at slot 6; playable media URL at slot 11; duration at+    // slot 8; read flag at slot 13 (1 read, 8 unread). Shape from live capture+    // (record-level slots past the items array omitted — the parser only reads+    // the id at 0 and the items at 2).+    private fun voicemailBody(+        id: String = "c.VMID1",+        transcript: String = "[0.96,[[\"Hey\",null,null,0.96],[\"there\",null,null,0.95]]]",+        audioUrl: String? = "\"https://www.google.com/voice/media/svm/ACCOUNT/TOKEN\"",+        type: Int = 2,+        readFlag: Int = 1,+    ): String {+        val audio = audioUrl ?: "null"+        return "[[[\"$id\",1,[[\"VMID1\",1792622182651,\"+12133945548\"," ++            "[\"+15550001111\",\"+15550001111\",null,null,null,null,0],$type,1,$transcript," ++            "null,44,\"\",null,$audio,3,$readFlag,null,\"+15550001111\",0]]]]]"+    }++    @Test+    fun parseVoicemails_mapsRecordSlots() {+        val vms = GoogleVoiceParser.parseVoicemails(voicemailBody())+        assertEquals(1, vms.size)+        val vm = vms.single()+        assertEquals("c.VMID1", vm.id)+        assertEquals("+15550001111", vm.phoneNumber)+        assertEquals(1792622182651L, vm.timestampMillis)+        assertEquals(44L, vm.durationSeconds)+        assertEquals("Hey there", vm.transcript)+        assertEquals("https://www.google.com/voice/media/svm/ACCOUNT/TOKEN", vm.audioUrl)+        assertTrue(vm.read)+    }++    @Test+    fun parseVoicemails_marksUnreadFlag8() {+        val vm = GoogleVoiceParser.parseVoicemails(voicemailBody(readFlag = 8)).single()+        assertFalse(vm.read)+    }++    @Test+    fun parseVoicemails_nullTranscriptAndAudio() {+        val vm = GoogleVoiceParser.parseVoicemails(+            voicemailBody(transcript = "null", audioUrl = null),+        ).single()+        assertEquals(null, vm.transcript)+        assertEquals(null, vm.audioUrl)+    }++    @Test+    fun parseVoicemails_skipsCallRecords() {+        // Folder-3 call shape in a folder-4 body: type 14, no transcript/audio.+        val vms = GoogleVoiceParser.parseVoicemails(voicemailBody(id = "c.CALL1", type = 14))+        assertTrue(vms.isEmpty())+    }++    @Test+    fun parseVoicemails_skipsEmptyItems() {+        val vms = GoogleVoiceParser.parseVoicemails("[[[\"c.EMPTY\",1,[]]]]")+        assertTrue(vms.isEmpty())+    } }