Modern Apps git

← Modern-Apps.git

messages: unify inbox sort, intent handling, new conversations

Commit
0876645947269d754cc3018899b8aea5eb8fad44
Author
Vayun Mathur <[email protected]>
When
2026-05-30 21:04 UTC (6 months ago)
Parents
301b81c

Diff

messages/src/main/AndroidManifest.xml
diff --git a/messages/src/main/AndroidManifest.xml b/messages/src/main/AndroidManifest.xmlindex 2739ebd629..7fb15cdfdb 100644--- a/messages/src/main/AndroidManifest.xml+++ b/messages/src/main/AndroidManifest.xml@@ -27,11 +27,50 @@         <activity             android:name=".MainActivity"             android:exported="true"+            android:launchMode="singleTop"             android:theme="@style/Theme.General">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>++            <!-- Share-sheet target. text/plain handles text shares from+                 any app; image/video/audio/* handles media shares from+                 Photos / Files / etc. The wildcard */* catches generic+                 "Share file" intents that don't pre-classify the MIME+                 (e.g. from cloud storage apps). -->+            <intent-filter>+                <action android:name="android.intent.action.SEND" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="text/plain" />+                <data android:mimeType="image/*" />+                <data android:mimeType="video/*" />+                <data android:mimeType="audio/*" />+                <data android:mimeType="application/*" />+            </intent-filter>+            <intent-filter>+                <action android:name="android.intent.action.SEND_MULTIPLE" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="image/*" />+                <data android:mimeType="video/*" />+                <data android:mimeType="audio/*" />+                <data android:mimeType="application/*" />+            </intent-filter>++            <!-- Phone-number deep links from the dialer / contacts /+                 webpage tel-links. smsto:+1...?body=... is the canonical+                 shape; sms: and mms*/ variants are accepted for parity+                 with the stock Messages app. -->+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <action android:name="android.intent.action.SENDTO" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data android:scheme="sms" />+                <data android:scheme="smsto" />+                <data android:scheme="mms" />+                <data android:scheme="mmsto" />+            </intent-filter>         </activity>          <service
messages/src/main/java/com/vayunmathur/messages/MainActivity.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt b/messages/src/main/java/com/vayunmathur/messages/MainActivity.ktindex 72621ba3d5..023eacac26 100644--- a/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt+++ b/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt@@ -1,34 +1,50 @@ package com.vayunmathur.messages  import android.Manifest+import android.content.Intent+import android.net.Uri import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.MutableState+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.viewmodel.compose.viewModel import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.PermissionsChecker import com.vayunmathur.library.util.ListPage import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.messages.data.buildMessagesDatabase+import com.vayunmathur.messages.ui.ComposeScreen import com.vayunmathur.messages.ui.ConversationScreen import com.vayunmathur.messages.ui.InboxScreen import com.vayunmathur.messages.ui.SettingsScreen import com.vayunmathur.messages.ui.setup.MessagesPairingScreen import com.vayunmathur.messages.ui.setup.VoiceLoginScreen+import com.vayunmathur.messages.util.IncomingIntent import com.vayunmathur.messages.util.MessagesViewModel+import com.vayunmathur.messages.util.ShareIntentParser import kotlinx.serialization.Serializable  class MainActivity : ComponentActivity() { +    /** Bridges Activity-side intent updates into the Compose backstack.+     *  Each newly delivered intent goes through this state; Compose+     *  observes and routes via [applyIntentRoute]. */+    private val pendingIntent: MutableState<Intent?> = mutableStateOf(null)+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()+        pendingIntent.value = intent         setContent {             DynamicTheme {                 // POST_NOTIFICATIONS is the only runtime perm we strictly@@ -48,11 +64,18 @@ class MainActivity : ComponentActivity() {                 }                 PermissionsChecker(perms, getString(R.string.permissions_post_notifications)) {                     val db = remember { buildMessagesDatabase(this@MainActivity) }-                    Navigation(db)+                    Navigation(db, pendingIntent)                 }             }         }     }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        // Re-delivering an intent while the activity is already alive+        // (singleTop). Hand it off to Compose for backstack routing.+        pendingIntent.value = intent+    } }  /** Navigation graph for the messages module. */@@ -63,14 +86,44 @@ sealed interface Route : NavKey {     @Serializable data object Settings : Route     @Serializable data object PairMessages : Route     @Serializable data object LoginVoice : Route++    /**+     * "Compose new" screen — recipient picker + body + media preview.+     * Used both for the inbox FAB ("New chat") and as the landing+     * surface for share-sheet intents / smsto: deep links.+     */+    @Serializable data class Compose(+        /** Pre-filled recipient (E.164 or any free-form string). null = empty field. */+        val initialNumber: String? = null,+        /** Pre-filled body. null = empty. */+        val initialBody: String? = null,+        /** content:// URIs of media to attach. Encoded as strings so the+         *  route remains Serializable. */+        val initialMediaUris: List<String> = emptyList(),+        /** Best-effort mime hint from the share intent. */+        val initialMime: String? = null,+    ) : Route }  @Composable private fun Navigation(     db: com.vayunmathur.messages.data.MessagesDatabase,+    pendingIntent: MutableState<Intent?>,     vm: MessagesViewModel = viewModel(), ) {     val backStack = rememberNavBackStack<Route>(Route.Inbox)++    // Consume each newly-delivered intent exactly once. snapshotFlow+    // turns the State into a Flow so we get re-triggered every time+    // onNewIntent updates the value; the `null` reset is the "ack".+    LaunchedEffect(Unit) {+        snapshotFlow { pendingIntent.value }.collect { intent ->+            if (intent == null) return@collect+            applyIntentRoute(backStack, ShareIntentParser.parse(intent))+            pendingIntent.value = null+        }+    }+     MainNavigation(backStack) {         entry<Route.Inbox>(metadata = ListPage { }) {             InboxScreen(backStack, vm, db)@@ -87,5 +140,57 @@ private fun Navigation(         entry<Route.LoginVoice> {             VoiceLoginScreen(backStack)         }+        entry<Route.Compose> { route ->+            ComposeScreen(+                backStack = backStack,+                vm = vm,+                db = db,+                initialNumber = route.initialNumber,+                initialBody = route.initialBody,+                initialMediaUris = route.initialMediaUris.map(Uri::parse),+                initialMime = route.initialMime,+            )+        }+    }+}++/**+ * Apply a parsed [IncomingIntent] to the navigation back-stack.+ *+ * Strategy:+ *  - OpenConversation → reset to `[Inbox, Conversation(id)]` so the+ *    user can press back to the inbox once they're done.+ *  - OpenNumber / Share → reset to `[Inbox, Compose(...)]` for the+ *    same reason.+ *  - null → no-op (activity was launched without an actionable intent).+ */+private fun applyIntentRoute(+    backStack: NavBackStack<Route>,+    incoming: IncomingIntent?,+) {+    when (incoming) {+        null -> Unit+        is IncomingIntent.OpenConversation -> {+            backStack.reset(Route.Inbox, Route.Conversation(incoming.conversationId))+        }+        is IncomingIntent.OpenNumber -> {+            backStack.reset(+                Route.Inbox,+                Route.Compose(+                    initialNumber = incoming.phone,+                    initialBody = incoming.prefilledBody,+                ),+            )+        }+        is IncomingIntent.Share -> {+            backStack.reset(+                Route.Inbox,+                Route.Compose(+                    initialBody = incoming.text,+                    initialMediaUris = incoming.mediaUris.map(Uri::toString),+                    initialMime = incoming.mime,+                ),+            )+        }     } }
messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.ktindex d6aeba52ae..56bc24ca01 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt@@ -4,6 +4,12 @@ import android.content.Context import android.util.Log import client.Client.ListConversationsRequest import client.Client.ListConversationsResponse+import client.Client.ListContactsRequest+import client.Client.ListContactsResponse+import client.Client.ListTopContactsRequest+import client.Client.ListTopContactsResponse+import client.Client.GetOrCreateConversationRequest+import client.Client.GetOrCreateConversationResponse import client.Client.ListMessagesRequest import client.Client.ListMessagesResponse import client.Client.MessagePayload@@ -334,6 +340,114 @@ object GMessagesClient {         return parsed?.success == true     } +    /**+     * Create (or return an existing) conversation for [numbers].+     *+     * Mirrors `Client.GetOrCreateConversation` (`pkg/libgm/methods.go:52`).+     * Single phone = 1:1 thread. Multiple phones = SMS group, or RCS+     * group when [createRcsGroup] + [rcsGroupName] is supplied.+     *+     * Returns the source-prefixed conversation id of the (possibly+     * newly-created) thread, or null on failure. The relay emits a+     * GET_UPDATES with the new conversation immediately after; we also+     * emit a synthetic [GMEvent.ConversationUpdate] so the inbox sees+     * the row before the long-poll catches up.+     */+    suspend fun getOrCreateConversation(+        numbers: List<String>,+        rcsGroupName: String? = null,+        createRcsGroup: Boolean = false,+    ): String? {+        if (numbers.isEmpty() || _state.value !is State.Connected) return null+        val req = GetOrCreateConversationRequest.newBuilder()+            .addAllNumbers(numbers.map {+                conversations.Conversations.ContactNumber.newBuilder()+                    .setMysteriousInt(2)  // 2 = "from contact list", per libgm+                    .setNumber(it)+                    .build()+            })+            .apply {+                if (createRcsGroup) {+                    setCreateRCSGroup(true)+                    rcsGroupName?.let { setRCSGroupName(it) }+                }+            }+            .build()+        val resp = sessionHandler.sendAndWait(ActionType.GET_OR_CREATE_CONVERSATION, req)+            ?: return null+        val parsed = runCatching {+            GetOrCreateConversationResponse.parseFrom(resp.decryptedData ?: return null)+        }.getOrNull() ?: return null++        if (parsed.status == GetOrCreateConversationResponse.Status.CREATE_RCS) {+            // The server is telling us "you asked for RCS but this set+            // of participants isn't RCS-capable — try again without".+            // The bridge does the same retry (handlematrix.go).+            Log.i(TAG, "getOrCreate: CREATE_RCS — retrying with SMS")+            return getOrCreateConversation(numbers, rcsGroupName = null, createRcsGroup = false)+        }+        if (!parsed.hasConversation()) {+            Log.w(TAG, "getOrCreate: status=${parsed.status} but no conversation")+            return null+        }+        val conv = parsed.conversation+        // Eagerly emit a synthetic ConversationUpdate so the inbox row+        // appears before the long-poll's GET_UPDATES delivers the same+        // info. emitConversation is idempotent via Room upsert so the+        // duplicate from the long-poll is harmless.+        emitConversation(conv)+        return "${source.idPrefix}:${conv.conversationID}"+    }++    /**+     * Server-side contact list, used to populate the recipient picker.+     * Mirrors `Client.ListContacts` (`pkg/libgm/methods.go:34`).+     * The bridge passes hardcoded magic ints (1, 350, 50) that we+     * preserve verbatim — the relay rejects requests without them.+     */+    suspend fun listContacts(): List<com.vayunmathur.messages.util.ContactSuggestion> {+        if (_state.value !is State.Connected) return emptyList()+        val req = ListContactsRequest.newBuilder()+            .setI1(1)+            .setI2(350)+            .setI3(50)+            .build()+        val resp = sessionHandler.sendAndWait(ActionType.LIST_CONTACTS, req) ?: return emptyList()+        val parsed = runCatching {+            ListContactsResponse.parseFrom(resp.decryptedData ?: return emptyList())+        }.getOrNull() ?: return emptyList()+        return (0 until parsed.contactsCount).mapNotNull { i ->+            parsed.getContacts(i).toSuggestion()+        }+    }++    /** Server-side "frequent contacts" — used as the picker's initial+     *  suggestion list before the user types anything. */+    suspend fun listTopContacts(count: Int = 20): List<com.vayunmathur.messages.util.ContactSuggestion> {+        if (_state.value !is State.Connected) return emptyList()+        val req = ListTopContactsRequest.newBuilder().setCount(count).build()+        val resp = sessionHandler.sendAndWait(ActionType.LIST_TOP_CONTACTS, req) ?: return emptyList()+        val parsed = runCatching {+            ListTopContactsResponse.parseFrom(resp.decryptedData ?: return emptyList())+        }.getOrNull() ?: return emptyList()+        return (0 until parsed.contactsCount).mapNotNull { i ->+            parsed.getContacts(i).toSuggestion()+        }+    }++    private fun conversations.Conversations.Contact.toSuggestion(): com.vayunmathur.messages.util.ContactSuggestion? {+        val phone = number?.number?.takeIf { it.isNotBlank() }+            ?: number?.number2?.takeIf { it.isNotBlank() }+            ?: return null+        val displayName = name.takeIf { it.isNotBlank() } ?: phone+        return com.vayunmathur.messages.util.ContactSuggestion(+            displayName = displayName,+            phoneE164 = phone,+            avatarUrl = null,+            source = source,+        )+    }+     @Suppress("UNUSED_PARAMETER")     @Deprecated("kept for binary compat — call sendMessage(conversationId, body) directly", level = DeprecationLevel.HIDDEN)     suspend fun sendMessageLegacy(conversationId: String, body: String): Boolean =@@ -532,7 +646,7 @@ object GMessagesClient {                 peerPhone = if (isGroup) null else peerPhone,                 avatarUrl = contact?.photoUri,                 lastPreview = if (c.hasLatestMessage()) c.latestMessage.displayContent.takeIf { it.isNotBlank() } else null,-                lastTimestamp = c.lastMessageTimestamp,+                lastTimestamp = toMillis(c.lastMessageTimestamp),                 unreadCount = if (c.unread) 1 else 0,                 isGroup = isGroup,                 participantCount = otherParticipants.size,@@ -587,7 +701,7 @@ object GMessagesClient {                 else com.vayunmathur.messages.data.MessageDirection.INCOMING,             state = if (outgoing) com.vayunmathur.messages.data.MessageState.SENT                 else com.vayunmathur.messages.data.MessageState.DELIVERED,-            timestamp = m.timestamp,+            timestamp = toMillis(m.timestamp),             senderName = if (m.hasSenderParticipant()) {                 m.senderParticipant.fullName.takeIf { it.isNotBlank() }                     ?: m.senderParticipant.firstName.takeIf { it.isNotBlank() }@@ -596,6 +710,15 @@ object GMessagesClient {         )     } +    /**+     * The relay returns timestamps in **microseconds** since epoch (see+     * `time.UnixMicro(conv.GetLastMessageTimestamp())` in the Go bridge+     * `pkg/connector/chatsync.go`). Everywhere else in this app (Room,+     * notifications, [java.util.Date], Voice's emission path) expects+     * **milliseconds**. Convert at the boundary so we never mix units.+     */+    private fun toMillis(usec: Long): Long = usec / 1000+     /** Roll up the per-emoji reaction entries on a Message into the      *  [count: Int] aggregate we store. */     private fun extractReactionsJson(m: conversations.Conversations.Message): String? {@@ -639,7 +762,7 @@ object GMessagesClient {                 messageId = m.messageID,                 body = body,                 outgoing = outgoing,-                timestamp = m.timestamp,+                timestamp = toMillis(m.timestamp),                 senderName = if (m.hasSenderParticipant()) {                     m.senderParticipant.fullName.takeIf { it.isNotBlank() }                         ?: m.senderParticipant.firstName.takeIf { it.isNotBlank() }@@ -660,7 +783,7 @@ object GMessagesClient {                     peerPhone = if (m.hasSenderParticipant()) {                         m.senderParticipant.id.number.takeIf { it.isNotBlank() }                     } else null,-                    timestamp = m.timestamp,+                    timestamp = toMillis(m.timestamp),                 )             )         }
messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.ktindex a27113201a..64a0050232 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt@@ -51,6 +51,18 @@ object VoiceEndpoints {     const val EndpointMarkAllRead = "$ApiBaseUrl/thread/markallread"     const val EndpointDeleteThread = "$ApiBaseUrl/thread/delete" +    /**+     * Contacts/PeopleStack endpoints. These live on a different host+     * ([ContactsDomain]) and the request headers + URL-query bundle are+     * adjusted by [com.vayunmathur.messages.gvoice.GVoiceRpcClient]+     * based on the destination domain — see [GVoiceRpcClient.buildUrl]+     * and [GVoiceRpcClient.applyHeaders].+     */+    private const val ContactsBaseUrl =+        "https://$ContactsDomain/\$rpc/peoplestack.PeopleStackAutocompleteService"+    const val EndpointAutocompleteContacts = "$ContactsBaseUrl/Autocomplete"+    const val EndpointLookupContacts = "$ContactsBaseUrl/Lookup"+     private const val RealtimeBaseUrl = "https://$RealtimeDomain"     const val EndpointRealtimeChannel = "$RealtimeBaseUrl/punctual/multi-watch/channel"     const val EndpointRealtimeChooseServer = "$RealtimeBaseUrl/punctual/v1/chooseServer"
messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.ktindex c43e66abab..4f41462bf0 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt@@ -296,6 +296,202 @@ object GVoiceClient {             else -> null         } +    /**+     * Send a text message to a brand-new thread keyed by [recipients].+     * Mirrors the bridge's "no portal id yet" path+     * (`pkg/connector/handlematrix.go:49`): build a [Requests.ReqSendSMS]+     * with `setRecipients(...)` and **no** `setThreadID`; the server+     * creates the thread and returns its assigned id in the response.+     *+     * Returns the new conversation id (prefixed with [source.idPrefix])+     * on success, or null on failure.+     */+    suspend fun sendNewThread(recipients: List<String>, body: String): String? {+        if (recipients.isEmpty()) return null+        if (_state.value !is State.Connected) return null+        val client = rpc ?: return null+        val req = Requests.ReqSendSMS.newBuilder()+            .addAllRecipients(recipients)+            .setText(body)+            .setTransactionID(+                Requests.ReqSendSMS.WrappedTxnID.newBuilder()+                    .setID(kotlin.random.Random.nextLong(100_000_000_000_000L))+                    .build()+            )+            .setTrackingData(+                Requests.ReqSendSMS.TrackingData.newBuilder().setData("!").build()+            )+            .build()+        return sendNewThreadInner(client, req)+    }++    /**+     * MMS variant of [sendNewThread]. Caption is optional; pass null to+     * send the media alone.+     */+    suspend fun sendNewThreadMedia(+        recipients: List<String>,+        mime: String,+        data: ByteArray,+        caption: String?,+    ): String? {+        if (recipients.isEmpty()) return null+        if (_state.value !is State.Connected) return null+        val client = rpc ?: return null+        val mediaType = mimeToVoiceMediaType(mime) ?: run {+            Log.w(TAG, "sendNewThreadMedia: unsupported MIME $mime")+            return null+        }+        val media = Requests.ReqSendSMS.Media.newBuilder()+            .setType(mediaType)+            .setData(com.google.protobuf.ByteString.copyFrom(data))+            .build()+        val req = Requests.ReqSendSMS.newBuilder()+            .addAllRecipients(recipients)+            .apply { caption?.takeIf { it.isNotBlank() }?.let { setText(it) } }+            .setMedia(media)+            .setTransactionID(+                Requests.ReqSendSMS.WrappedTxnID.newBuilder()+                    .setID(kotlin.random.Random.nextLong(100_000_000_000_000L))+                    .build()+            )+            .setTrackingData(+                Requests.ReqSendSMS.TrackingData.newBuilder().setData("!").build()+            )+            .build()+        return sendNewThreadInner(client, req)+    }++    private suspend fun sendNewThreadInner(+        client: GVoiceRpcClient,+        req: Requests.ReqSendSMS,+    ): String? = try {+        val resp = client.postPbLite(+            url = VoiceEndpoints.EndpointSendSms,+            body = req,+            responseTemplate = Responses.RespSendSMS.getDefaultInstance(),+        )+        // The server-assigned thread id appears in resp.threadID for+        // newly-created threads. If absent we have no way to surface+        // the result; return null so the caller can show an error.+        val threadId = resp.threadID.takeIf { it.isNotBlank() }+        if (threadId == null) {+            Log.w(TAG, "sendNewThread: missing threadID in response (itemId=${resp.threadItemID})")+            null+        } else {+            // Kick a backfill so the realtime channel surfaces the+            // brand-new thread metadata immediately.+            kickoffBackfill()+            "${source.idPrefix}:$threadId"+        }+    } catch (t: Throwable) {+        Log.w(TAG, "sendNewThread failed: ${t.message}")+        null+    }++    /**+     * Server-side contact autocomplete. Mirrors `Client.AutocompleteContacts`+     * in `pkg/libgv/client.go:172`. Empty [query] returns the top ~500+     * contacts (used to populate the picker initially); non-empty+     * narrows to ~15 matches.+     */+    suspend fun autocompleteContacts(query: String): List<com.vayunmathur.messages.util.ContactSuggestion> {+        if (_state.value !is State.Connected) return emptyList()+        val client = rpc ?: return emptyList()+        val maxResults: Int = if (query.isEmpty()) 500 else 15+        val req = Requests.ReqAutocompleteContacts.newBuilder()+            .setUnknownInt1(243)+            .setQuery(query)+            .addAllUnknownInts3(listOf(1, 2))+            .setMaxResults(maxResults)+            .build()+        val resp = try {+            client.postPbLite(+                url = VoiceEndpoints.EndpointAutocompleteContacts,+                body = req,+                responseTemplate = Responses.RespAutocompleteContacts.getDefaultInstance(),+            )+        } catch (t: Throwable) {+            Log.w(TAG, "autocompleteContacts failed: ${t.message}")+            return emptyList()+        }+        return (0 until resp.resultsCount).flatMap { i ->+            personToSuggestions(resp.getResults(i))+        }+    }++    /**+     * Resolve one-or-more phone numbers to known contacts via+     * peoplestack Lookup. Mirrors `Client.LookupContact`. Returned map+     * is keyed by E.164 phone with a [ContactSuggestion] value when a+     * match exists; missing keys = no match.+     */+    suspend fun lookupContact(phones: List<String>): Map<String, com.vayunmathur.messages.util.ContactSuggestion> {+        if (phones.isEmpty() || _state.value !is State.Connected) return emptyMap()+        val client = rpc ?: return emptyMap()+        val req = Requests.ReqLookupContacts.newBuilder()+            .setUnknownInt1(243)+            .addAllUnknownInts2(listOf(1, 2))+            .addAllTargets(phones.map { p ->+                contacts.Contacts.ContactID.newBuilder().setPhone(p).build()+            })+            .build()+        val resp = try {+            client.postPbLite(+                url = VoiceEndpoints.EndpointLookupContacts,+                body = req,+                responseTemplate = Responses.RespLookupContacts.getDefaultInstance(),+            )+        } catch (t: Throwable) {+            Log.w(TAG, "lookupContact failed: ${t.message}")+            return emptyMap()+        }+        val out = mutableMapOf<String, com.vayunmathur.messages.util.ContactSuggestion>()+        for (i in 0 until resp.matchesCount) {+            val match = resp.getMatches(i)+            val phone = match.id.phone.takeIf { it.isNotBlank() } ?: continue+            personToSuggestions(match.autocompletion).firstOrNull()?.let { out[phone] = it }+        }+        return out+    }++    /**+     * Flatten a [PersonWrapper] into one [ContactSuggestion] per phone+     * contact-method. Email-only entries are dropped — we can't send+     * SMS to them.+     */+    private fun personToSuggestions(+        wrapper: contacts.Contacts.PersonWrapper,+    ): List<com.vayunmathur.messages.util.ContactSuggestion> {+        val person = wrapper.person ?: return emptyList()+        // The display name lives on the contact method's displayInfo;+        // typically all methods on a person share the same name, so+        // just use the first non-blank one we see.+        val displayName = (0 until person.contactMethodsCount)+            .asSequence()+            .map { person.getContactMethods(it) }+            .mapNotNull { it.displayInfo?.name?.value?.takeIf { v -> v.isNotBlank() } }+            .firstOrNull()+            ?: "Unknown"+        val avatar = (0 until person.contactMethodsCount)+            .asSequence()+            .map { person.getContactMethods(it) }+            .mapNotNull { it.displayInfo?.photo?.url?.takeIf { v -> v.isNotBlank() } }+            .firstOrNull()+        return (0 until person.contactMethodsCount).mapNotNull { idx ->+            val cm = person.getContactMethods(idx)+            val rawPhone = cm.phone?.canonicalValue?.takeIf { it.isNotBlank() }+                ?: cm.phone?.displayValue?.takeIf { it.isNotBlank() }+                ?: return@mapNotNull null+            com.vayunmathur.messages.util.ContactSuggestion(+                displayName = displayName,+                phoneE164 = rawPhone,+                avatarUrl = avatar,+                source = source,+            )+        }+    }+     /** Load (or refresh) messages for a thread. */     fun fetchMessages(conversationId: String, count: Int = 100) {         if (_state.value !is State.Connected) return
messages/src/main/java/com/vayunmathur/messages/ui/ComposeRow.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/ComposeRow.kt b/messages/src/main/java/com/vayunmathur/messages/ui/ComposeRow.ktnew file mode 100644index 0000000000..34cb3d9cb5--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/ui/ComposeRow.kt@@ -0,0 +1,80 @@+package com.vayunmathur.messages.ui++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.foundation.shape.RoundedCornerShape+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconAttachment+import com.vayunmathur.messages.R++/**+ * Shared compose row used by both [ConversationScreen] and+ * [ComposeScreen]. Extracted so the two screens stay in lockstep on+ * compose-affordance behavior (attach button, send disabled while in+ * flight, etc.) without one drifting from the other.+ *+ * [sendEnabled] is the call-site's gate (e.g. "draft non-blank" for+ * conversation replies, "recipient picked AND (draft non-blank OR media+ * attached)" for new conversations). The row also unconditionally+ * disables Send while [sending] is true so the user can't double-tap.+ */+@Composable+internal fun ComposeRow(+    draft: String,+    onDraftChange: (String) -> Unit,+    sending: Boolean,+    onSend: () -> Unit,+    onAttach: () -> Unit,+    sendEnabled: Boolean = draft.isNotBlank(),+) {+    Surface(+        tonalElevation = 2.dp,+        modifier = Modifier.fillMaxWidth(),+    ) {+        Row(+            modifier = Modifier+                .padding(horizontal = 8.dp, vertical = 8.dp)+                .fillMaxWidth(),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            IconButton(onClick = onAttach, enabled = !sending) {+                IconAttachment()+            }+            OutlinedTextField(+                value = draft,+                onValueChange = onDraftChange,+                modifier = Modifier+                    .weight(1f, fill = true)+                    .padding(horizontal = 4.dp),+                placeholder = { Text(stringResource(R.string.conversation_compose_placeholder)) },+                maxLines = 5,+                enabled = !sending,+                shape = RoundedCornerShape(24.dp),+            )+            IconButton(onClick = onSend, enabled = sendEnabled && !sending) {+                if (sending) {+                    CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)+                } else {+                    Text(+                        stringResource(R.string.conversation_send),+                        fontWeight = FontWeight.SemiBold,+                        color = MaterialTheme.colorScheme.primary,+                    )+                }+            }+        }+    }+}
messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.ktnew file mode 100644index 0000000000..58eb5e54cd--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/ui/ComposeScreen.kt@@ -0,0 +1,429 @@+package com.vayunmathur.messages.ui++import android.net.Uri+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.PickVisualMediaRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Button+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Scaffold+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+import androidx.compose.material3.SnackbarHost+import androidx.compose.material3.SnackbarHostState+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.material3.TopAppBarDefaults+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import coil.compose.AsyncImage+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.messages.Route+import com.vayunmathur.messages.data.MessageSource+import com.vayunmathur.messages.data.MessagesDatabase+import com.vayunmathur.messages.util.ContactSuggestion+import com.vayunmathur.messages.util.MessagesViewModel+import com.vayunmathur.messages.util.NewMediaPart+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/**+ * Compose-new screen.+ *+ * Used for three entry points:+ *  1. Inbox FAB → empty form, user types a recipient + body.+ *  2. `smsto:` deep link → recipient prefilled, body optionally prefilled.+ *  3. Share-sheet target → body prefilled (text), media URIs prefilled.+ *+ * Source selection (Voice vs Messages) follows the rules the user+ * confirmed during planning:+ *  - Selected recipient phone has an existing thread on exactly one+ *    source → that source is auto-picked, segmented control hidden.+ *  - 0 or 2 existing sources → user must pick.+ *+ * When the user hits Send, we navigate into the resulting thread (so+ * back goes to inbox, not back to this screen).+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ComposeScreen(+    backStack: NavBackStack<Route>,+    vm: MessagesViewModel,+    db: MessagesDatabase,+    initialNumber: String?,+    initialBody: String?,+    initialMediaUris: List<Uri>,+    initialMime: String?,+) {+    val scope = rememberCoroutineScope()+    val snackbar = remember { SnackbarHostState() }++    // Recipient state. The selected recipient is the one chip we+    // commit to; the query field is what the user is currently typing.+    var query by remember { mutableStateOf(initialNumber.orEmpty()) }+    var selectedRecipient by remember { mutableStateOf<ContactSuggestion?>(null) }+    val suggestions = remember { mutableStateListOf<ContactSuggestion>() }+    // 150 ms debounce on the search so we don't hammer the autocomplete+    // endpoint on every keystroke. The first effect at empty-query+    // pulls the initial "top contacts" list.+    LaunchedEffect(query) {+        delay(150)+        suggestions.clear()+        suggestions.addAll(vm.searchContacts(query))+    }++    // Source selection state. We resolve which source(s) a number is+    // already on whenever the selected recipient changes; that drives+    // both the segmented-control visibility and the auto-pick.+    var availableSources by remember { mutableStateOf<Set<MessageSource>>(emptySet()) }+    var chosenSource by remember { mutableStateOf<MessageSource?>(null) }+    LaunchedEffect(selectedRecipient) {+        val phone = selectedRecipient?.phoneE164 ?: return@LaunchedEffect+        availableSources = vm.resolveSourcesForNumber(phone)+        chosenSource = when {+            availableSources.size == 1 -> availableSources.single()+            // Picker-source hint when the contact came from a backend+            // (gvoice autocomplete / gmessages contact list) — preselect+            // that source when no thread exists yet.+            selectedRecipient?.source != null && availableSources.isEmpty() ->+                selectedRecipient?.source+            else -> null+        }+    }++    // Body + media state.+    var draft by remember { mutableStateOf(initialBody.orEmpty()) }+    val media = remember { mutableStateListOf<Uri>().apply { addAll(initialMediaUris) } }+    var sending by remember { mutableStateOf(false) }++    val pickImage = rememberLauncherForActivityResult(+        contract = ActivityResultContracts.PickVisualMedia(),+    ) { uri -> uri?.let(media::add) }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("New conversation") },+                navigationIcon = { IconNavigation(backStack) },+                colors = TopAppBarDefaults.topAppBarColors(+                    containerColor = MaterialTheme.colorScheme.surface,+                ),+            )+        },+        snackbarHost = { SnackbarHost(snackbar) },+    ) { padding ->+        Column(+            modifier = Modifier.padding(padding).fillMaxSize(),+        ) {+            // Recipient row: chip (when selected) OR live search field.+            if (selectedRecipient != null) {+                SelectedRecipientChip(+                    recipient = selectedRecipient!!,+                    onClear = {+                        selectedRecipient = null+                        availableSources = emptySet()+                        chosenSource = null+                    },+                )+                // Source picker — only when ambiguous. Pre-existing or+                // single-source threads are shown as a small "via …" label.+                SourcePicker(+                    available = availableSources,+                    chosen = chosenSource,+                    onChange = { chosenSource = it },+                )+            } else {+                OutlinedTextField(+                    value = query,+                    onValueChange = { query = it },+                    placeholder = { Text("Name or phone number") },+                    modifier = Modifier+                        .fillMaxWidth()+                        .padding(horizontal = 12.dp, vertical = 8.dp),+                    singleLine = true,+                    shape = RoundedCornerShape(24.dp),+                )+                LazyColumn(modifier = Modifier.weight(1f, fill = false)) {+                    items(suggestions, key = { (it.phoneE164 ?: it.displayName) + "|" + (it.source?.name ?: "device") }) { sug ->+                        SuggestionRow(sug) {+                            selectedRecipient = sug+                            query = sug.displayName+                        }+                    }+                }+            }++            // Media preview row — horizontal scroller of thumbs.+            if (media.isNotEmpty()) {+                LazyColumn(+                    modifier = Modifier.padding(horizontal = 12.dp),+                    verticalArrangement = Arrangement.spacedBy(6.dp),+                ) {+                    items(media.toList(), key = { it.toString() }) { uri ->+                        MediaThumb(uri = uri, onRemove = { media.remove(uri) })+                    }+                }+            }++            Spacer(Modifier.weight(1f))++            // Compose row reuses the conversation-screen pattern.+            ComposeRow(+                draft = draft,+                onDraftChange = { draft = it },+                sending = sending,+                onSend = {+                    val source = chosenSource+                    val recipient = selectedRecipient?.phoneE164 ?: query.trim().takeIf { it.isNotEmpty() }+                    when {+                        recipient == null -> scope.launch {+                            snackbar.showSnackbar("Pick a recipient first")+                        }+                        source == null -> scope.launch {+                            snackbar.showSnackbar("Choose a source (Voice or Messages)")+                        }+                        // Voice supports image MMS only. Anything else+                        // (video / audio / file) goes through gmessages+                        // only. We check the first attachment's mime to+                        // decide; mixed attachments are out of scope.+                        else -> scope.launch {+                            val mediaPart = media.firstOrNull()?.let { vm.readUri(it) }+                            if (source == MessageSource.VOICE &&+                                mediaPart != null &&+                                !mediaPart.mime.startsWith("image/")+                            ) {+                                snackbar.showSnackbar(+                                    "Voice supports image MMS only — pick Messages, or remove the attachment."+                                )+                                return@launch+                            }+                            sending = true+                            vm.sendNewMessage(+                                source = source,+                                recipients = listOf(recipient),+                                body = draft.trim().takeIf { it.isNotEmpty() },+                                media = mediaPart,+                            ) { newConvId ->+                                sending = false+                                if (newConvId == null) {+                                    scope.launch { snackbar.showSnackbar("Send failed") }+                                } else {+                                    backStack.pop()+                                    backStack.add(Route.Conversation(newConvId))+                                }+                            }+                        }+                    }+                },+                onAttach = {+                    pickImage.launch(+                        PickVisualMediaRequest(+                            ActivityResultContracts.PickVisualMedia.ImageAndVideo+                        )+                    )+                },+            )+        }+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun SourcePicker(+    available: Set<MessageSource>,+    chosen: MessageSource?,+    onChange: (MessageSource) -> Unit,+) {+    // Hide entirely when the source is forced (exactly one existing+    // thread). Show a tiny "via …" label instead so the user knows.+    if (available.size == 1) {+        val s = available.single()+        Text(+            "Sending via ${labelFor(s)}",+            modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            style = MaterialTheme.typography.labelMedium,+        )+        return+    }+    val options = MessageSource.values().toList()+    SingleChoiceSegmentedButtonRow(+        modifier = Modifier+            .fillMaxWidth()+            .padding(horizontal = 12.dp, vertical = 6.dp),+    ) {+        options.forEachIndexed { idx, source ->+            SegmentedButton(+                selected = chosen == source,+                onClick = { onChange(source) },+                shape = SegmentedButtonDefaults.itemShape(idx, options.size),+            ) {+                Text(labelFor(source))+            }+        }+    }+}++@Composable+private fun SelectedRecipientChip(+    recipient: ContactSuggestion,+    onClear: () -> Unit,+) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .padding(horizontal = 12.dp, vertical = 10.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Surface(+            shape = CircleShape,+            color = MaterialTheme.colorScheme.primaryContainer,+            modifier = Modifier.size(36.dp),+        ) {+            if (recipient.avatarUrl != null) {+                AsyncImage(+                    model = recipient.avatarUrl,+                    contentDescription = null,+                    contentScale = ContentScale.Crop,+                    modifier = Modifier.fillMaxSize(),+                )+            } else {+                Box(contentAlignment = Alignment.Center) {+                    Text(+                        recipient.displayName.take(1).uppercase(),+                        color = MaterialTheme.colorScheme.onPrimaryContainer,+                        fontWeight = FontWeight.SemiBold,+                    )+                }+            }+        }+        Spacer(Modifier.width(12.dp))+        Column(modifier = Modifier.weight(1f)) {+            Text(recipient.displayName, fontWeight = FontWeight.SemiBold)+            recipient.phoneE164?.let {+                Text(it, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+            }+        }+        IconButton(onClick = onClear) { IconClose() }+    }+}++@Composable+private fun SuggestionRow(suggestion: ContactSuggestion, onPick: () -> Unit) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .clickable(onClick = onPick)+            .padding(horizontal = 16.dp, vertical = 10.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Surface(+            shape = CircleShape,+            color = MaterialTheme.colorScheme.surfaceVariant,+            modifier = Modifier.size(32.dp),+        ) {+            if (suggestion.avatarUrl != null) {+                AsyncImage(+                    model = suggestion.avatarUrl,+                    contentDescription = null,+                    contentScale = ContentScale.Crop,+                    modifier = Modifier.fillMaxSize(),+                )+            } else {+                Box(contentAlignment = Alignment.Center) {+                    Text(suggestion.displayName.take(1).uppercase(), fontSize = 13.sp)+                }+            }+        }+        Spacer(Modifier.width(12.dp))+        Column(modifier = Modifier.weight(1f)) {+            Text(suggestion.displayName)+            suggestion.phoneE164?.let {+                Text(+                    it,+                    style = MaterialTheme.typography.labelMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+        }+        suggestion.source?.let { src ->+            Text(+                labelFor(src),+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.primary,+            )+        }+    }+}++@Composable+private fun MediaThumb(uri: Uri, onRemove: () -> Unit) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .padding(vertical = 4.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Surface(+            shape = RoundedCornerShape(8.dp),+            modifier = Modifier+                .size(56.dp)+                .clip(RoundedCornerShape(8.dp)),+        ) {+            AsyncImage(+                model = uri,+                contentDescription = null,+                contentScale = ContentScale.Crop,+                modifier = Modifier.fillMaxSize(),+            )+        }+        Spacer(Modifier.width(12.dp))+        Text(uri.lastPathSegment ?: "attachment", modifier = Modifier.weight(1f))+        IconButton(onClick = onRemove) { IconClose() }+    }+}++private fun labelFor(source: MessageSource): String = when (source) {+    MessageSource.MESSAGES_WEB -> "Messages"+    MessageSource.VOICE -> "Voice"+}
messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.ktindex 2d338187fd..0c2fe5235d 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt@@ -521,56 +521,6 @@ private fun ConvAvatar(conversation: Conversation?) {     } } -@Composable-private fun ComposeRow(-    draft: String,-    onDraftChange: (String) -> Unit,-    sending: Boolean,-    onSend: () -> Unit,-    onAttach: () -> Unit,-) {-    Surface(-        tonalElevation = 2.dp,-        modifier = Modifier.fillMaxWidth(),-    ) {-        Row(-            modifier = Modifier-                .padding(horizontal = 8.dp, vertical = 8.dp)-                .fillMaxWidth(),-            verticalAlignment = Alignment.CenterVertically,-        ) {-            IconButton(onClick = onAttach, enabled = !sending) {-                Text(-                    "+",-                    fontSize = 22.sp,-                    fontWeight = FontWeight.Bold,-                    color = MaterialTheme.colorScheme.primary,-                )-            }-            OutlinedTextField(-                value = draft,-                onValueChange = onDraftChange,-                modifier = Modifier.weight(1f),-                placeholder = { Text(stringResource(R.string.conversation_compose_placeholder)) },-                maxLines = 5,-                enabled = !sending,-                shape = RoundedCornerShape(24.dp),-            )-            IconButton(onClick = onSend, enabled = draft.isNotBlank() && !sending) {-                if (sending) {-                    CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)-                } else {-                    Text(-                        stringResource(R.string.conversation_send),-                        fontWeight = FontWeight.SemiBold,-                        color = MaterialTheme.colorScheme.primary,-                    )-                }-            }-        }-    }-}- private fun formatTime(ts: Long): String =     DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(ts)) 
messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.ktindex 34002eeb04..c5da94b860 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt@@ -21,6 +21,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem@@ -90,6 +91,11 @@ fun InboxScreen(                 },             )         },+        floatingActionButton = {+            FloatingActionButton(onClick = { backStack.add(Route.Compose()) }) {+                com.vayunmathur.library.ui.IconAdd()+            }+        },     ) { padding ->         Column(             modifier = Modifier
messages/src/main/java/com/vayunmathur/messages/util/ContactResolver.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/ContactResolver.kt b/messages/src/main/java/com/vayunmathur/messages/util/ContactResolver.ktindex fb0cc48dc6..bc7516c047 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/ContactResolver.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/ContactResolver.kt@@ -32,6 +32,101 @@ object ContactResolver {         val photoUri: String?,     ) +    /** Search hit returned by [search]. Phones are stored verbatim from+     *  the Contacts provider — they may or may not be in E.164. The UI+     *  is responsible for normalization before sending. */+    data class SearchHit(+        val displayName: String,+        val phoneE164: String,+        val photoUri: String?,+    )++    /**+     * Search device contacts by name or phone substring.+     *+     * Backed by [ContactsContract.Contacts.CONTENT_FILTER_URI] for name+     * matches and [ContactsContract.CommonDataKinds.Phone.CONTENT_URI]+     * for number matches. Returns up to [limit] suggestions, sorted+     * with starred contacts first (matches the system Phone app order).+     */+    fun search(context: Context, query: String, limit: Int = 30): List<SearchHit> {+        if (!hasPermission(context)) return emptyList()+        if (query.isBlank()) return topContacts(context, limit)+        val out = mutableListOf<SearchHit>()+        val projection = arrayOf(+            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,+            ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,+            ContactsContract.CommonDataKinds.Phone.NUMBER,+            ContactsContract.CommonDataKinds.Phone.PHOTO_URI,+            ContactsContract.CommonDataKinds.Phone.STARRED,+        )+        // Match either the display name OR the phone number against the+        // user's query. NORMALIZED_NUMBER strips punctuation so a search+        // for "5551234" matches "+1 (555) 123-4" too.+        val selection =+            "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ? OR " ++                "${ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER} LIKE ? OR " ++                "${ContactsContract.CommonDataKinds.Phone.NUMBER} LIKE ?"+        val wildcard = "%${query.trim()}%"+        val args = arrayOf(wildcard, wildcard, wildcard)+        return try {+            context.contentResolver.query(+                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,+                projection,+                selection,+                args,+                "${ContactsContract.CommonDataKinds.Phone.STARRED} DESC, " ++                    "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} ASC",+            )?.use { cursor ->+                while (cursor.moveToNext() && out.size < limit) {+                    val name = cursor.getString(0)?.takeIf { it.isNotBlank() } ?: continue+                    val phone = (cursor.getString(1)?.takeIf { it.isNotBlank() }+                        ?: cursor.getString(2)?.takeIf { it.isNotBlank() }) ?: continue+                    val photo = cursor.getString(3)?.takeIf { it.isNotBlank() }+                    out += SearchHit(displayName = name, phoneE164 = phone, photoUri = photo)+                }+            }+            out+        } catch (t: Throwable) {+            Log.w(TAG, "search($query) failed: ${t.message}")+            out+        }+    }++    /** Subset of [search] for the "initial suggestions" state when the+     *  user hasn't typed anything yet. Returns starred contacts first. */+    private fun topContacts(context: Context, limit: Int): List<SearchHit> {+        val projection = arrayOf(+            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,+            ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,+            ContactsContract.CommonDataKinds.Phone.NUMBER,+            ContactsContract.CommonDataKinds.Phone.PHOTO_URI,+        )+        val out = mutableListOf<SearchHit>()+        return try {+            context.contentResolver.query(+                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,+                projection,+                null,+                null,+                "${ContactsContract.CommonDataKinds.Phone.STARRED} DESC, " ++                    "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} ASC LIMIT $limit",+            )?.use { cursor ->+                while (cursor.moveToNext()) {+                    val name = cursor.getString(0)?.takeIf { it.isNotBlank() } ?: continue+                    val phone = (cursor.getString(1)?.takeIf { it.isNotBlank() }+                        ?: cursor.getString(2)?.takeIf { it.isNotBlank() }) ?: continue+                    val photo = cursor.getString(3)?.takeIf { it.isNotBlank() }+                    out += SearchHit(displayName = name, phoneE164 = phone, photoUri = photo)+                }+            }+            out+        } catch (t: Throwable) {+            Log.w(TAG, "topContacts() failed: ${t.message}")+            out+        }+    }+     fun lookup(context: Context, phoneNumber: String): Result? {         if (phoneNumber.isBlank()) return null         if (!hasPermission(context)) return null
messages/src/main/java/com/vayunmathur/messages/util/ContactSuggestion.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/ContactSuggestion.kt b/messages/src/main/java/com/vayunmathur/messages/util/ContactSuggestion.ktnew file mode 100644index 0000000000..a3a96dc755--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/util/ContactSuggestion.kt@@ -0,0 +1,27 @@+package com.vayunmathur.messages.util++import com.vayunmathur.messages.data.MessageSource++/**+ * One row in the new-conversation recipient picker.+ *+ * Backed by any of three sources of truth:+ *  - **Device contacts** via [ContactResolver] (no [MessageSource] —+ *    the user picks which backend to send through).+ *  - **gmessages** `ListTopContacts` / `ListContacts` (source =+ *    [MessageSource.MESSAGES_WEB]).+ *  - **gvoice** `AutocompleteContacts` (source = [MessageSource.VOICE]).+ *+ * The picker deduplicates by [phoneE164] across all three sources.+ * When the same phone exists in multiple sources, the device-contact+ * entry wins for `displayName`/`avatarUrl` (it's the user's own naming),+ * while the protocol-side hits contribute their [source] for the+ * "this person has a thread on…" hint in the UI.+ */+data class ContactSuggestion(+    val displayName: String,+    val phoneE164: String?,+    val avatarUrl: String?,+    /** Which backend surfaced this contact. `null` = device contact only. */+    val source: MessageSource? = null,+)
messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.ktindex d9fb9fa6e6..d939b0a1da 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt@@ -260,6 +260,141 @@ object MessagesSessionManager {         }     } +    /**+     * Search contacts across all available sources.+     *+     * Merges (and deduplicates by phone) hits from:+     *  - **gmessages** server-side contact list (when connected). The+     *    server doesn't accept a query filter so we pull once and+     *    filter client-side. The list is short (a few hundred).+     *  - **gvoice** server-side autocomplete (when connected). Empty+     *    [query] pulls the top ~500; non-empty narrows server-side.+     *  - **Device contacts** via [ContactResolver] for name-only and+     *    number-only matches not already covered by either backend.+     *+     * Returned in stable order: matches whose [ContactSuggestion.source]+     * is non-null come first (we know they're reachable on at least one+     * source), then device-only entries. Within each group, prefix+     * matches on the display name rank above substring matches.+     */+    suspend fun searchContacts(query: String): List<ContactSuggestion> {+        val q = query.trim()+        val isPhone = q.startsWith("+") && q.length >= 4+        val results = mutableListOf<ContactSuggestion>()++        // gmessages: pull the top-contacts list once when query is+        // empty (initial picker open), otherwise fall through to a+        // filter on the full contacts list. The list isn't reactive+        // so we just do a one-shot fetch each call.+        if (GMessagesClient.state.value is com.vayunmathur.messages.gmessages.GMessagesClient.State.Connected) {+            val list = if (q.isEmpty()) GMessagesClient.listTopContacts() else GMessagesClient.listContacts()+            results += list.filter { c -> q.isEmpty() || matches(c, q) }+        }+        // gvoice: server-side filter for non-empty queries; full list+        // for empty.+        if (GVoiceClient.state.value is com.vayunmathur.messages.gvoice.GVoiceClient.State.Connected) {+            results += GVoiceClient.autocompleteContacts(q)+                .filter { c -> q.isEmpty() || matches(c, q) }+        }+        // Always include device contact matches so users see names from+        // their phone even when neither backend's contact list knows+        // about them. ContactResolver.search supports both name+number.+        results += ContactResolver.search(appContext, q).map { dc ->+            ContactSuggestion(+                displayName = dc.displayName,+                phoneE164 = dc.phoneE164,+                avatarUrl = dc.photoUri,+                source = null,+            )+        }+        // Also: literal-number entry. If the user typed something that+        // looks like a phone number and it isn't already in the list,+        // add a "Send to {number}" row so they can send to a brand-new+        // contact without first saving them.+        if (isPhone && results.none { it.phoneE164 == q }) {+            results += ContactSuggestion(displayName = q, phoneE164 = q, avatarUrl = null, source = null)+        }+        // Dedupe by phone, preferring entries that carry a source.+        return results+            .groupBy { it.phoneE164 ?: it.displayName }+            .map { (_, group) -> group.minByOrNull { if (it.source == null) 1 else 0 }!! }+    }++    private fun matches(c: ContactSuggestion, q: String): Boolean {+        val needle = q.lowercase()+        return c.displayName.lowercase().contains(needle) ||+            (c.phoneE164?.lowercase()?.contains(needle) == true)+    }++    /**+     * Which sources already have an existing thread for [phoneE164]?+     * Drives the "smart routing" decision in the new-conversation+     * picker: zero sources → user picks; one source → route there;+     * two sources → user picks.+     */+    suspend fun resolveSourcesForNumber(phoneE164: String): Set<MessageSource> {+        if (phoneE164.isBlank()) return emptySet()+        // Normalize for comparison: strip non-digits + leading '+'.+        val needle = normalizePhone(phoneE164)+        val all = db.conversationDao().observeAll().firstOrNull().orEmpty()+        return all.asSequence()+            .filter { !it.isGroup && it.peerPhoneE164 != null }+            .filter { normalizePhone(it.peerPhoneE164!!) == needle }+            .map { it.source }+            .toSet()+    }++    private fun normalizePhone(raw: String): String =+        raw.filter { it.isDigit() }.trimStart('0')++    /**+     * Start a brand-new conversation (and send the first text + optional+     * media in the same call).+     *+     * gmessages: GET_OR_CREATE_CONVERSATION → SEND_MESSAGE/SEND_MEDIA.+     * gvoice: builds a ReqSendSMS with `recipients` set so the server+     * creates the thread in one round trip.+     *+     * Returns the new conversation id on success, or null on failure.+     */+    suspend fun sendNewMessage(+        source: MessageSource,+        recipients: List<String>,+        body: String?,+        media: NewMediaPart? = null,+    ): String? {+        if (recipients.isEmpty()) return null+        return when (source) {+            MessageSource.MESSAGES_WEB -> {+                val convId = GMessagesClient.getOrCreateConversation(recipients) ?: return null+                val ok = if (media != null) {+                    GMessagesClient.sendMedia(+                        conversationId = convId,+                        data = media.bytes,+                        mime = media.mime,+                        fileName = media.fileName,+                        caption = body,+                    )+                } else {+                    GMessagesClient.sendMessage(convId, body.orEmpty())+                }+                if (ok) convId else null+            }+            MessageSource.VOICE -> {+                if (media != null) {+                    GVoiceClient.sendNewThreadMedia(+                        recipients = recipients,+                        mime = media.mime,+                        data = media.bytes,+                        caption = body,+                    )+                } else {+                    GVoiceClient.sendNewThread(recipients, body.orEmpty())+                }+            }+        }+    }+     /**      * Bulk-write a backfill batch of messages in ONE transaction.      * Called by the protocol clients when LIST_MESSAGES / GetThread@@ -313,6 +448,14 @@ object MessagesSessionManager {             is GMEvent.ConversationUpdate -> {                 val id = "${event.source.idPrefix}:${event.conversationId}"                 val existing = db.conversationDao().get(id)+                // One-shot guard: rows persisted before the gmessages+                // microseconds→milliseconds fix have last_ts > 1e14+                // (≈ year 5138 in ms). Treat those as "no existing+                // timestamp" so the first refresh after the fix lands+                // immediately re-anchors to the correct scale rather+                // than holding the stale huge value via maxOf.+                val priorTs = existing?.lastMessageTimestamp+                    ?.takeIf { it < STALE_MICROSECOND_THRESHOLD_MS } ?: 0L                 val merged = Conversation(                     id = id,                     source = event.source,@@ -320,7 +463,7 @@ object MessagesSessionManager {                     peerPhoneE164 = event.peerPhone ?: existing?.peerPhoneE164,                     avatarUrl = event.avatarUrl ?: existing?.avatarUrl,                     lastMessagePreview = event.lastPreview ?: existing?.lastMessagePreview,-                    lastMessageTimestamp = maxOf(event.lastTimestamp, existing?.lastMessageTimestamp ?: 0L),+                    lastMessageTimestamp = maxOf(event.lastTimestamp, priorTs),                     unreadCount = event.unreadCount,                     isGroup = event.isGroup,                     participantCount = event.participantCount,@@ -378,9 +521,37 @@ object MessagesSessionManager {         conversationId.startsWith("${MessageSource.VOICE.idPrefix}:") -> MessageSource.VOICE         else -> null     }++    /** ≈ year 5138 in epoch-ms. Any persisted `last_ts` larger than this+     *  is almost certainly a stale microsecond value from before the+     *  gmessages timestamp fix; treat it as missing. */+    private const val STALE_MICROSECOND_THRESHOLD_MS = 100_000_000_000_000L }  /** Action passed to [MessagesSessionManager.sendReaction]. Mirrors the  *  three-state add/remove/switch enum in [SendReactionRequest.Action]  *  without exposing the protobuf type to non-protocol callers. */ enum class ReactionAction { ADD, REMOVE, SWITCH }++/** Media payload for [MessagesSessionManager.sendNewMessage]. Keeping+ *  bytes + meta together so callers don't need a 4-arg overload. */+data class NewMediaPart(+    val bytes: ByteArray,+    val mime: String,+    val fileName: String,+) {+    // ByteArray equality is reference-based by default; provide proper+    // value equality so test fixtures and === sites behave sanely.+    override fun equals(other: Any?): Boolean {+        if (this === other) return true+        if (other !is NewMediaPart) return false+        return mime == other.mime && fileName == other.fileName && bytes.contentEquals(other.bytes)+    }++    override fun hashCode(): Int {+        var result = bytes.contentHashCode()+        result = 31 * result + mime.hashCode()+        result = 31 * result + fileName.hashCode()+        return result+    }+}
messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt b/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.ktindex 68bbcb0a2a..2584d59af6 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt@@ -89,6 +89,62 @@ class MessagesViewModel(application: Application) : AndroidViewModel(application         }     } +    /**+     * Search contacts across both backends + the device contact db.+     * The UI calls this on every keystroke; debounce is the caller's+     * concern (use Compose `LaunchedEffect(query) { delay(150); … }`).+     */+    suspend fun searchContacts(query: String): List<ContactSuggestion> =+        MessagesSessionManager.searchContacts(query)++    /** Which sources already have an existing 1:1 thread with this number? */+    suspend fun resolveSourcesForNumber(phoneE164: String): Set<com.vayunmathur.messages.data.MessageSource> =+        MessagesSessionManager.resolveSourcesForNumber(phoneE164)++    /**+     * Read a content:// URI's bytes + mime + filename off the IO+     * dispatcher. Returns null if the URI is unreadable.+     *+     * Exposed here (vs. having callers do it inline) because the+     * Compose-side new-conversation screen needs to read multiple URIs+     * from a share intent before any single send is fired, and it's+     * cleaner to keep the contentResolver dance in one place.+     */+    suspend fun readUri(uri: android.net.Uri): NewMediaPart? =+        kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+            val cr = getApplication<Application>().contentResolver+            val bytes = runCatching { cr.openInputStream(uri)?.use { it.readBytes() } }+                .getOrNull() ?: return@withContext null+            val mime = cr.getType(uri) ?: "application/octet-stream"+            val name = queryDisplayName(uri) ?: uri.lastPathSegment ?: "attachment"+            NewMediaPart(bytes = bytes, mime = mime, fileName = name)+        }++    private fun queryDisplayName(uri: android.net.Uri): String? = try {+        val cr = getApplication<Application>().contentResolver+        cr.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->+            if (c.moveToFirst()) c.getString(0)?.takeIf { it.isNotBlank() } else null+        }+    } catch (_: Throwable) {+        null+    }++    /**+     * Create + send to a brand-new thread in one call. Returns the new+     * conversation id (prefixed) so the caller can navigate into it.+     */+    fun sendNewMessage(+        source: com.vayunmathur.messages.data.MessageSource,+        recipients: List<String>,+        body: String?,+        media: NewMediaPart? = null,+        onResult: (String?) -> Unit = {},+    ) {+        viewModelScope.launch {+            onResult(MessagesSessionManager.sendNewMessage(source, recipients, body, media))+        }+    }+     fun fetchMessages(conversationId: String) {         MessagesSessionManager.fetchMessages(conversationId)     }
messages/src/main/java/com/vayunmathur/messages/util/ShareIntentParser.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/util/ShareIntentParser.kt b/messages/src/main/java/com/vayunmathur/messages/util/ShareIntentParser.ktnew file mode 100644index 0000000000..a03da97c65--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/util/ShareIntentParser.kt@@ -0,0 +1,99 @@+package com.vayunmathur.messages.util++import android.content.Intent+import android.net.Uri+import android.os.Build++/**+ * Parses an inbound [Intent] into a [IncomingIntent] the UI can act on.+ *+ * Three intent shapes are recognized:+ *  - **Notification deep-link** — an explicit launch with+ *    [MessagesService.EXTRA_OPEN_CONVERSATION] set. Routes the user+ *    straight to the right conversation.+ *  - **sms / mms SENDTO/VIEW** — e.g. `smsto:+15551234567?body=hi%20there`.+ *    Routes to the Compose screen with the number + body pre-filled.+ *  - **ACTION_SEND / ACTION_SEND_MULTIPLE** — share-sheet target.+ *    Routes to the Compose screen with text and any attached media URIs+ *    pre-loaded.+ *+ * Returns null when the intent is the bare launcher MAIN intent (no+ * navigation override needed; the activity opens at its default route).+ */+sealed interface IncomingIntent {+    data class OpenConversation(val conversationId: String) : IncomingIntent+    data class OpenNumber(val phone: String, val prefilledBody: String?) : IncomingIntent+    data class Share(+        val text: String?,+        val mediaUris: List<Uri>,+        /** Best-effort mime hint from the originating app (e.g. "image/png" or `\u002a/\u002a`). */+        val mime: String?,+    ) : IncomingIntent+}++object ShareIntentParser {++    fun parse(intent: Intent?): IncomingIntent? {+        if (intent == null) return null++        // 1. Notification deep-link — explicit extra.+        intent.getStringExtra(MessagesService.EXTRA_OPEN_CONVERSATION)+            ?.takeIf { it.isNotBlank() }+            ?.let { return IncomingIntent.OpenConversation(it) }++        return when (intent.action) {+            Intent.ACTION_VIEW, Intent.ACTION_SENDTO -> parseSmsIntent(intent)+            Intent.ACTION_SEND -> parseShareIntent(intent, multiple = false)+            Intent.ACTION_SEND_MULTIPLE -> parseShareIntent(intent, multiple = true)+            else -> null+        }+    }++    /** Decode an `sms:` / `smsto:` / `mms:` / `mmsto:` URI. */+    private fun parseSmsIntent(intent: Intent): IncomingIntent? {+        val uri = intent.data ?: return null+        val scheme = uri.scheme?.lowercase() ?: return null+        if (scheme !in SMS_SCHEMES) return null+        // sms:+15551234567 / smsto:+15551234567 — the number lives in+        // the scheme-specific-part, NOT path/host. URLDecode it to+        // collapse %2B → + etc.+        val raw = uri.schemeSpecificPart.orEmpty().substringBefore('?')+        val phone = Uri.decode(raw).trim().takeIf { it.isNotBlank() }+            ?: return null+        // `body` (Android-canonical) and `sms_body` (some senders) both+        // carry the prefilled text. Either is accepted.+        val body = uri.getQueryParameter("body")+            ?: uri.getQueryParameter("sms_body")+        return IncomingIntent.OpenNumber(phone, body)+    }++    /** Decode ACTION_SEND / ACTION_SEND_MULTIPLE share-sheet intents. */+    @Suppress("DEPRECATION")+    private fun parseShareIntent(intent: Intent, multiple: Boolean): IncomingIntent? {+        val text = intent.getStringExtra(Intent.EXTRA_TEXT)+        val mime = intent.type+        val mediaUris: List<Uri> = if (multiple) {+            val list = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java)+            } else {+                intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM)+            }+            list?.toList().orEmpty()+        } else {+            val single = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)+            } else {+                intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri+            }+            listOfNotNull(single)+        }+        if (text.isNullOrBlank() && mediaUris.isEmpty()) return null+        return IncomingIntent.Share(+            text = text?.takeIf { it.isNotBlank() },+            mediaUris = mediaUris,+            mime = mime,+        )+    }++    private val SMS_SCHEMES = setOf("sms", "smsto", "mms", "mmsto")+}