Modern Apps git

← Modern-Apps.git

messages: fix issues with sending messages

Commit
5232f5ff8783a1317b29b8403f34b030ade8c0f4
Author
Vayun Mathur <[email protected]>
When
2026-05-30 19:55 UTC (6 months ago)
Parents
5e9ce91

Diff

messages/src/main/java/com/vayunmathur/messages/data/Entities.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/data/Entities.kt b/messages/src/main/java/com/vayunmathur/messages/data/Entities.ktindex 832fdf80b1..8d1a5e7023 100644--- a/messages/src/main/java/com/vayunmathur/messages/data/Entities.kt+++ b/messages/src/main/java/com/vayunmathur/messages/data/Entities.kt@@ -35,6 +35,14 @@ data class Conversation(     /** Conversation type as the relay reports it: "SMS", "RCS",      *  or null/UNKNOWN. Used for the per-row chip. */     @ColumnInfo(name = "conv_type") val conversationType: String? = null,+    /** Per-source identifier we need to pass back when SENDING a message+     *  on this conversation.+     *  - For [MessageSource.MESSAGES_WEB]: the conversation's+     *    `defaultOutgoingID` (Google's per-thread "my SIM" participantID,+     *    used as `MessagePayload.participantID` in SendMessageRequest).+     *  - For [MessageSource.VOICE]: unused — the thread ID is enough.+     *  Stored so we don't have to keep the full proto Conversation around. */+    @ColumnInfo(name = "outgoing_id") val outgoingId: String? = null, )  /**
messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt b/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.ktindex 7656ed1c04..aab6e41f10 100644--- a/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt+++ b/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt@@ -28,6 +28,9 @@ interface ConversationDao {     @Query("UPDATE conversations SET unread_count = 0 WHERE id = :id")     suspend fun markRead(id: String) +    @Query("DELETE FROM conversations WHERE id = :id")+    suspend fun deleteById(id: String)+     @Query("DELETE FROM conversations WHERE source = :source")     suspend fun deleteAllForSource(source: MessageSource) }@@ -48,6 +51,12 @@ interface MessageDao {      @Query("UPDATE messages SET state = :state WHERE id = :id")     suspend fun updateState(id: String, state: MessageState)++    @Query("UPDATE messages SET reactions_json = :json WHERE id = :id")+    suspend fun updateReactions(id: String, json: String?)++    @Query("DELETE FROM messages WHERE id = :id")+    suspend fun deleteById(id: String) }  /**@@ -74,7 +83,7 @@ class MessagesConverters {  @androidx.room.Database(     entities = [Conversation::class, Message::class],-    version = 3,+    version = 4,     exportSchema = false, ) @TypeConverters(MessagesConverters::class)
messages/src/main/java/com/vayunmathur/messages/gmessages/Constants.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/Constants.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/Constants.ktindex 924f4abda4..c38ebf49b0 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/Constants.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Constants.kt@@ -39,6 +39,11 @@ object Endpoints {     const val ReceiveMessagesUrl = "$MessagingBase/ReceiveMessages"     const val SendMessageUrl = "$MessagingBase/SendMessage"     const val AckMessagesUrl = "$MessagingBase/AckMessages"++    /** Used by [com.vayunmathur.messages.gmessages.Media] for the+     *  resumable-upload + finalize media flow. The body is form-encoded+     *  on START and raw on FINALIZE; both go to the same URL. */+    const val UploadMediaUrl = "$ImBase/upload" }  /** MIME types for the two wire encodings the relay accepts. */
messages/src/main/java/com/vayunmathur/messages/gmessages/Crypto.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/Crypto.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/Crypto.ktindex 56b8f95759..20ff5c472a 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/Crypto.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Crypto.kt@@ -86,6 +86,112 @@ class AesCtrHmac(     } } +/**+ * Chunked AES-GCM helper used for media uploads.+ *+ * Direct port of `crypto/aesgcm.go` from mautrix-gmessages: the plaintext+ * is split into 32 KiB chunks, each encrypted with a fresh random+ * 12-byte nonce + AAD = `[isLast(1 byte), chunkIndex(uint32 big-endian)]`.+ * The 2-byte stream header `(0, log2(chunkSize))` precedes the chunk+ * stream so the decoder knows the chunk boundary.+ *+ * The on-disk wire format must match exactly — Google's media server+ * doesn't decrypt this; we encrypt before upload and the recipient's+ * Messages client decrypts after download using the [decryptionKey]+ * Google routes through the SendMessageRequest media field.+ */+class AesGcm(val key: ByteArray) {+    init {+        require(key.size == 32) { "unsupported AES-GCM key length (got=${key.size} expected=32)" }+    }++    fun encryptData(data: ByteArray): ByteArray {+        val chunkOverhead = NONCE_SIZE + TAG_SIZE+        var chunkSize = OUTGOING_RAW_CHUNK_SIZE - chunkOverhead+        val chunkCount = ((data.size + chunkSize - 1) / chunkSize).coerceAtLeast(1)+        val out = java.io.ByteArrayOutputStream(2 + data.size + chunkOverhead * chunkCount)+        // Stream header: `0` magic byte + log2(chunkSize). chunkSize here+        // means the OUTGOING_RAW_CHUNK_SIZE, NOT the plaintext size.+        out.write(0)+        out.write(LOG2_OUTGOING_RAW_CHUNK_SIZE)+        var chunkIndex = 0+        var i = 0+        while (i < data.size) {+            val isLast = (i + chunkSize) >= data.size+            if (isLast) chunkSize = data.size - i+            val aad = aad(chunkIndex, isLast)+            val nonce = ByteArray(NONCE_SIZE)+            SecureRandom().nextBytes(nonce)+            val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {+                init(+                    Cipher.ENCRYPT_MODE,+                    SecretKeySpec(key, "AES"),+                    javax.crypto.spec.GCMParameterSpec(TAG_SIZE * 8, nonce),+                )+                updateAAD(aad)+            }+            val ct = cipher.doFinal(data, i, chunkSize)+            // Prepend nonce, exactly like Go's `c.gcm.Seal(nonce, …)`.+            out.write(nonce)+            out.write(ct)+            chunkIndex+++            i += chunkSize+        }+        return out.toByteArray()+    }++    fun decryptData(blob: ByteArray): ByteArray {+        if (blob.isEmpty()) return blob+        require(blob[0] == 0.toByte()) { "invalid AES-GCM stream header byte=${blob[0]}" }+        val chunkSize = 1 shl (blob[1].toInt() and 0xFF)+        val body = blob.copyOfRange(2, blob.size)+        val out = java.io.ByteArrayOutputStream(body.size)+        var chunkIndex = 0+        var i = 0+        var thisChunk = chunkSize+        while (i < body.size) {+            val isLast = (i + thisChunk) >= body.size+            if (isLast) thisChunk = body.size - i+            require(thisChunk >= NONCE_SIZE) { "GCM chunk too small ($thisChunk)" }+            val aad = aad(chunkIndex, isLast)+            val nonce = body.copyOfRange(i, i + NONCE_SIZE)+            val ct = body.copyOfRange(i + NONCE_SIZE, i + thisChunk)+            val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {+                init(+                    Cipher.DECRYPT_MODE,+                    SecretKeySpec(key, "AES"),+                    javax.crypto.spec.GCMParameterSpec(TAG_SIZE * 8, nonce),+                )+                updateAAD(aad)+            }+            out.write(cipher.doFinal(ct))+            i += thisChunk+            chunkIndex+++        }+        return out.toByteArray()+    }++    /** Per-chunk AAD: 1 magic byte (isLast) + big-endian uint32 chunkIndex. */+    private fun aad(chunkIndex: Int, isLast: Boolean): ByteArray {+        val aad = ByteArray(5)+        if (isLast) aad[0] = 1+        aad[1] = ((chunkIndex ushr 24) and 0xFF).toByte()+        aad[2] = ((chunkIndex ushr 16) and 0xFF).toByte()+        aad[3] = ((chunkIndex ushr 8) and 0xFF).toByte()+        aad[4] = (chunkIndex and 0xFF).toByte()+        return aad+    }++    companion object {+        const val NONCE_SIZE = 12+        const val TAG_SIZE = 16+        const val OUTGOING_RAW_CHUNK_SIZE = 1 shl 15  // 32 KiB+        const val LOG2_OUTGOING_RAW_CHUNK_SIZE = 15++        fun generateKey(): ByteArray = AesCtrHmac.generateKey(32)+    }+}+ /**  * Serializable JWK form of an ECDSA P-256 key pair. Matches the JSON shape  * used by libgm in `crypto/ecdsa.go` so the persisted on-disk
messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.ktindex a16b3153ee..19ec1dd71b 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt@@ -28,6 +28,8 @@ sealed interface GMEvent {         val isGroup: Boolean = false,         val participantCount: Int = 0,         val conversationType: String? = null,+        /** Source-specific "my participant" id. See [Conversation.outgoingId]. */+        val outgoingId: String? = null,     ) : GMEvent      /** A message row appeared / was updated. Used for backfill + live sync. */@@ -53,4 +55,16 @@ sealed interface GMEvent {         val peerPhone: String?,         val timestamp: Long,     ) : GMEvent++    /** A message was deleted on the remote side (or by us). */+    data class MessageDeleted(+        override val source: MessageSource,+        val messageId: String,+    ) : GMEvent++    /** A conversation was deleted on the remote side. */+    data class ConversationDeleted(+        override val source: MessageSource,+        val conversationId: String,+    ) : GMEvent }
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 e5917c4907..d6aeba52ae 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt@@ -6,10 +6,27 @@ import client.Client.ListConversationsRequest import client.Client.ListConversationsResponse import client.Client.ListMessagesRequest import client.Client.ListMessagesResponse+import client.Client.MessagePayload+import client.Client.MessageReadRequest+import client.Client.SendMessageRequest+import client.Client.SendMessageResponse+import client.Client.SendReactionRequest+import client.Client.SendReactionResponse+import client.Client.TypingUpdateRequest+import client.Client.UpdateConversationRequest+import client.Client.UpdateConversationResponse+import client.Client.DeleteConversationData+import client.Client.ConversationActionStatus+import client.Client.DeleteMessageRequest+import client.Client.DeleteMessageResponse import com.vayunmathur.messages.data.MessageSource import com.vayunmathur.messages.util.ContactResolver import conversations.Conversations.Conversation import conversations.Conversations.Message+import conversations.Conversations.MessageInfo+import conversations.Conversations.MessageContent+import conversations.Conversations.ReactionData+import events.Events.UpdateEvents import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -73,6 +90,7 @@ object GMessagesClient {     private val rpc = RpcClient()     @Volatile private var auth: AuthData = AuthData.generateInitial()     private val sessionHandler = SessionHandler(rpc) { auth }+    private val media = Media { auth }     private val longPoll = LongPoll(         rpc = rpc,         authProvider = { auth },@@ -81,6 +99,11 @@ object GMessagesClient {     )     private var backfillJob: Job? = null +    /** Per-conversation "my SIM" participant ID surfaced by+     *  LIST_CONVERSATIONS.defaultOutgoingID. Used to populate the+     *  participantID on outgoing SendMessageRequest payloads. */+    private val outgoingIds = java.util.concurrent.ConcurrentHashMap<String, String>()+     @Volatile private var conversationsFetchedOnce = false      fun init(context: Context) {@@ -133,14 +156,230 @@ object GMessagesClient {         return result.qrUrl     } -    @Suppress("UNUSED_PARAMETER")+    /**+     * Send a text message via SEND_MESSAGE.+     *+     * Mirrors `ConvertMatrixMessage` + `Client.SendMessage` in+     * `pkg/connector/handlematrix.go` / `pkg/libgm/methods.go`:+     * builds a [SendMessageRequest] with a [MessageContent] info part,+     * a fresh `tmp_…` transaction ID, and the per-conversation+     * `participantID` we captured from LIST_CONVERSATIONS.+     *+     * Returns `true` iff the relay reports `SUCCESS`.+     */     suspend fun sendMessage(conversationId: String, body: String): Boolean {-        // TODO(messages-libgm): Building the full SendMessageRequest-        // payload requires the conversations.MessageContent + nested-        // MessagePayload structures. Deferred — receiving works first.         if (_state.value !is State.Connected) return false-        Log.w(TAG, "sendMessage not yet implemented (received conv=$conversationId body=${body.length} chars)")-        return false+        val webId = conversationId.substringAfter(':', conversationId)+        val info = MessageInfo.newBuilder()+            .setMessageContent(MessageContent.newBuilder().setContent(body))+            .build()+        return sendWithInfos(webId, listOf(info))+    }++    /**+     * Send an image (or any media) via SEND_MESSAGE. Uploads the bytes+     * first via [Media.upload], then attaches the resulting+     * [MediaContent] to a SendMessageRequest. If [caption] is non-blank,+     * a separate MessageContent info part is appended so the recipient+     * sees image + caption like Google Messages does.+     */+    suspend fun sendMedia(+        conversationId: String,+        data: ByteArray,+        mime: String,+        fileName: String,+        caption: String?,+    ): Boolean {+        if (_state.value !is State.Connected) return false+        val webId = conversationId.substringAfter(':', conversationId)+        val mediaContent = try {+            media.upload(data, fileName, mime)+        } catch (t: Throwable) {+            Log.w(TAG, "media upload failed: ${t.message}")+            return false+        }+        val infos = mutableListOf(+            MessageInfo.newBuilder().setMediaContent(mediaContent).build()+        )+        if (!caption.isNullOrBlank()) {+            infos += MessageInfo.newBuilder()+                .setMessageContent(MessageContent.newBuilder().setContent(caption))+                .build()+        }+        return sendWithInfos(webId, infos)+    }++    /** Common SEND_MESSAGE plumbing — builds the envelope and awaits a response. */+    private suspend fun sendWithInfos(webId: String, infos: List<MessageInfo>): Boolean {+        val tmpId = "tmp_${kotlin.random.Random.nextLong(1_000_000_000_000L).toString().padStart(12, '0')}"+        val participantId = outgoingIds[webId].orEmpty()+        val payload = MessagePayload.newBuilder()+            .setTmpID(tmpId)+            .setConversationID(webId)+            .setParticipantID(participantId)+            .setTmpID2(tmpId)+            .addAllMessageInfo(infos)+            .build()+        val req = SendMessageRequest.newBuilder()+            .setConversationID(webId)+            .setMessagePayload(payload)+            .setTmpID(tmpId)+            .build()+        val resp = sessionHandler.sendAndWait(ActionType.SEND_MESSAGE, req)+            ?: return false.also { Log.w(TAG, "SEND_MESSAGE timed out") }+        val data = resp.decryptedData ?: return false+        val parsed = runCatching { SendMessageResponse.parseFrom(data) }.getOrNull()+            ?: return false+        Log.i(TAG, "SEND_MESSAGE status=${parsed.status}")+        return parsed.status == SendMessageResponse.Status.SUCCESS+    }++    /**+     * Mark messages in [conversationId] as read up to [messageId].+     * Mirrors `Client.MarkRead`.+     */+    suspend fun markRead(conversationId: String, messageId: String?): Boolean {+        if (_state.value !is State.Connected) return false+        val webId = conversationId.substringAfter(':', conversationId)+        val msgWebId = messageId?.substringAfter(':', messageId).orEmpty()+        val req = MessageReadRequest.newBuilder()+            .setConversationID(webId)+            .setMessageID(msgWebId)+            .build()+        val resp = sessionHandler.sendAndWait(ActionType.MESSAGE_READ, req)+        return resp != null+    }++    /**+     * Delete [conversationId] on the phone via UPDATE_CONVERSATION+     * with [ConversationActionStatus.DELETE]. The phone is part of the+     * proto because the relay routes the delete to the correct SIM /+     * thread on the device.+     */+    suspend fun deleteConversation(conversationId: String, phone: String?): Boolean {+        if (_state.value !is State.Connected) return false+        val webId = conversationId.substringAfter(':', conversationId)+        val data = DeleteConversationData.newBuilder()+            .setConversationID(webId)+            .apply { if (!phone.isNullOrBlank()) setPhone(phone) }+            .build()+        val req = UpdateConversationRequest.newBuilder()+            .setAction(ConversationActionStatus.DELETE)+            .setConversationID(webId)+            .setDeleteData(data)+            .build()+        val resp = sessionHandler.sendAndWait(ActionType.UPDATE_CONVERSATION, req)+            ?: return false+        val body = resp.decryptedData ?: return false+        val parsed = runCatching { UpdateConversationResponse.parseFrom(body) }.getOrNull()+        return parsed?.success == true+    }++    /**+     * Add / remove / switch a reaction on [messageId].+     * Mirrors `Client.SendReaction`. We send only the unicode emoji and+     * `EmojiType.CUSTOM` is reserved for actual stickers — we always+     * pass `REACTION_TYPE_UNSPECIFIED` so the relay infers the type+     * from the unicode codepoint (Google's web client does the same).+     */+    suspend fun sendReaction(+        messageId: String,+        emoji: String,+        action: SendReactionRequest.Action,+    ): Boolean {+        if (_state.value !is State.Connected) return false+        val msgWebId = messageId.substringAfter(':', messageId)+        val req = SendReactionRequest.newBuilder()+            .setMessageID(msgWebId)+            .setAction(action)+            .setReactionData(ReactionData.newBuilder().setUnicode(emoji))+            .build()+        val resp = sessionHandler.sendAndWait(ActionType.SEND_REACTION, req) ?: return false+        val body = resp.decryptedData ?: return false+        val parsed = runCatching { SendReactionResponse.parseFrom(body) }.getOrNull()+        return parsed?.success == true+    }++    /**+     * Notify the peer that the user is currently typing.+     * Fire-and-forget (no waiter).+     */+    suspend fun sendTyping(conversationId: String): Boolean {+        if (_state.value !is State.Connected) return false+        val webId = conversationId.substringAfter(':', conversationId)+        val req = TypingUpdateRequest.newBuilder()+            .setData(+                TypingUpdateRequest.Data.newBuilder()+                    .setConversationID(webId)+                    .setTyping(true)+            )+            .build()+        return sessionHandler.sendNoWait(ActionType.TYPING_UPDATES, req)+    }++    /**+     * Delete a single message via DELETE_MESSAGE. The relay echoes the+     * delete through the long-poll's MESSAGE_DELETED event when+     * complete — local Room rows are cleared via that event path so+     * the UI updates once for both local-initiated and remote-initiated+     * deletes.+     */+    suspend fun deleteMessage(messageId: String): Boolean {+        if (_state.value !is State.Connected) return false+        val webId = messageId.substringAfter(':', messageId)+        val req = DeleteMessageRequest.newBuilder().setMessageID(webId).build()+        val resp = sessionHandler.sendAndWait(ActionType.DELETE_MESSAGE, req) ?: return false+        val body = resp.decryptedData ?: return false+        val parsed = runCatching { DeleteMessageResponse.parseFrom(body) }.getOrNull()+        return parsed?.success == true+    }++    @Suppress("UNUSED_PARAMETER")+    @Deprecated("kept for binary compat — call sendMessage(conversationId, body) directly", level = DeprecationLevel.HIDDEN)+    suspend fun sendMessageLegacy(conversationId: String, body: String): Boolean =+        sendMessage(conversationId, body)++    /**+     * Pump for inbound real-time updates pushed by the relay.+     *+     * Each GET_UPDATES message wraps an [UpdateEvents] oneof. We handle+     * the three high-signal kinds:+     *  - [UpdateEvents.MessageEvent]: new/edited messages → emit+     *    MessageUpdate (+ IncomingMessage for non-outgoing).+     *  - [UpdateEvents.ConversationEvent]: conversation metadata bumps+     *    → re-emit the row via [emitConversation].+     *  - [UpdateEvents.TypingEvent]: kept here for completeness; no UI+     *    yet, so we just log.+     *+     * Anything else is logged at debug and ignored. The bridge itself+     * has handlers for stickers / settings / participant events; those+     * are out of scope for v1.+     */+    private suspend fun handleGetUpdates(data: ByteArray) {+        val updates = runCatching { UpdateEvents.parseFrom(data) }.getOrNull() ?: run {+            Log.w(TAG, "GET_UPDATES: failed to parse UpdateEvents")+            return+        }+        when {+            updates.hasMessageEvent() -> {+                val msgs = updates.messageEvent.dataList+                Log.i(TAG, "GET_UPDATES: ${msgs.size} message event(s)")+                msgs.forEach { emitMessage(it) }+            }+            updates.hasConversationEvent() -> {+                val convs = updates.conversationEvent.dataList+                Log.i(TAG, "GET_UPDATES: ${convs.size} conversation event(s)")+                convs.forEach { emitConversation(it) }+            }+            updates.hasTypingEvent() -> {+                val data2 = updates.typingEvent.data+                Log.d(TAG, "GET_UPDATES typing conv=${data2.conversationID} type=${data2.type}")+            }+            updates.hasUserAlertEvent() -> {+                Log.d(TAG, "GET_UPDATES user-alert: ${updates.userAlertEvent.alertType}")+            }+            else -> Log.d(TAG, "GET_UPDATES: unhandled event kind")+        }     }      /**@@ -248,11 +487,16 @@ object GMessagesClient {                 }                 com.vayunmathur.messages.util.MessagesSessionManager.bulkUpsertMessages(rows)             }+            ActionType.GET_UPDATES -> handleGetUpdates(data)             else -> Log.d(TAG, "unhandled data action ${msg.action}")         }     }      private suspend fun emitConversation(c: conversations.Conversations.Conversation) {+        // Capture defaultOutgoingID so the SEND_MESSAGE path can route+        // the outgoing through the right SIM. Keyed by web ID (no prefix).+        c.defaultOutgoingID.takeIf { it.isNotBlank() }?.let { outgoingIds[c.conversationID] = it }+         // Collect the non-self participants — used for both phone-lookup         // (1:1 chats) and group-display labeling.         val otherParticipants = (0 until c.participantsCount)@@ -293,6 +537,7 @@ object GMessagesClient {                 isGroup = isGroup,                 participantCount = otherParticipants.size,                 conversationType = type,+                outgoingId = c.defaultOutgoingID.takeIf { it.isNotBlank() },             )         )     }
messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.ktnew file mode 100644index 0000000000..fdc14ca7ed--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Media.kt@@ -0,0 +1,244 @@+package com.vayunmathur.messages.gmessages++import android.util.Base64+import android.util.Log+import authentication.Authentication+import authentication.Authentication.AuthMessage+import client.Client.StartMediaUploadRequest+import client.Client.UploadMediaResponse+import conversations.Conversations.MediaContent+import conversations.Conversations.MediaFormats+import io.ktor.client.HttpClient+import io.ktor.client.engine.cio.CIO+import io.ktor.client.plugins.HttpTimeout+import io.ktor.client.request.headers+import io.ktor.client.request.request+import io.ktor.client.request.setBody+import io.ktor.client.statement.HttpResponse+import io.ktor.client.statement.bodyAsBytes+import io.ktor.http.ContentType+import io.ktor.http.HttpMethod+import io.ktor.http.contentType++/**+ * Port of `pkg/libgm/media.go` (mautrix-gmessages).+ *+ * MMS image send flow:+ *   1. Generate a fresh 32-byte AES-GCM key.+ *   2. Encrypt the bytes with the chunked-GCM stream framing from+ *      [AesGcm.encryptData].+ *   3. POST a START-UPLOAD with `x-goog-upload-command: start` and a+ *      base64'd [StartMediaUploadRequest] envelope as body. The+ *      response Content-Type isn't used — we read the+ *      `x-goog-upload-url` header and other resumable-upload metadata.+ *   4. POST the encrypted bytes to that URL with+ *      `x-goog-upload-command: upload, finalize` and offset 0. The+ *      response body is base64'd `UploadMediaResponse` proto carrying+ *      the assigned `mediaID`.+ *   5. Return a [MediaContent] referencing that media ID + the+ *      decryption key — the caller stuffs this into the+ *      [conversations.Conversations.MessageInfo.MediaContent] field of+ *      a SendMessageRequest.+ *+ * The Messages-for-Web client decrypts on download using the+ * [MediaContent.decryptionKey] we route through the SendMessageRequest.+ */+class Media(private val authProvider: () -> AuthData) {++    private val http: HttpClient = HttpClient(CIO) {+        engine { requestTimeout = 120_000 }+        install(HttpTimeout) {+            requestTimeoutMillis = 120_000+            connectTimeoutMillis = 30_000+            socketTimeoutMillis = 120_000+        }+    }++    fun close() {+        runCatching { http.close() }+    }++    /** End-to-end: encrypt + start + finalize, return [MediaContent]. */+    suspend fun upload(data: ByteArray, fileName: String, mime: String): MediaContent {+        val format = mimeToFormat(mime)+        val key = AesGcm.generateKey()+        val cipher = AesGcm(key)+        val encrypted = cipher.encryptData(data)+        val start = startUpload(encrypted, mime)+        val finalized = finalizeUpload(start)+        Log.i(TAG, "media upload ok mime=$mime size=${data.size} mediaID=${finalized.mediaID}")+        return MediaContent.newBuilder()+            .setFormat(format)+            .setMediaID(finalized.mediaID)+            .setMediaName(fileName)+            .setSize(data.size.toLong())+            .setDecryptionKey(com.google.protobuf.ByteString.copyFrom(key))+            .setMimeType(mime)+            .build()+    }++    /** Encode + base64 a StartMediaUploadRequest envelope. */+    private fun buildStartPayload(): String {+        val auth = authProvider()+        val req = StartMediaUploadRequest.newBuilder()+            .setAttachmentType(1)+            .setAuthData(+                AuthMessage.newBuilder()+                    .setRequestID(java.util.UUID.randomUUID().toString())+                    .setTachyonAuthToken(+                        com.google.protobuf.ByteString.copyFrom(auth.tachyonToken()!!)+                    )+                    .setNetwork(PairFlow.QrNetwork)+                    .setConfigVersion(PairFlow.ConfigVersion)+            )+        auth.mobile()?.let { req.setMobile(it) }+        return Base64.encodeToString(req.build().toByteArray(), Base64.NO_WRAP)+    }++    /** POST the START upload request. Returns the resumable URL + meta. */+    private suspend fun startUpload(encrypted: ByteArray, mime: String): StartedUpload {+        val payload = buildStartPayload()+        val sizeStr = encrypted.size.toString()+        val resp: HttpResponse = http.request(Endpoints.UploadMediaUrl) {+            method = HttpMethod.Post+            contentType(ContentType.parse("application/x-www-form-urlencoded;charset=UTF-8"))+            uploadHeaders(+                contentLength = sizeStr,+                command = "start",+                offset = null,+                contentMime = mime,+                protocol = "resumable",+            )+            setBody(payload.toByteArray(Charsets.UTF_8))+        }+        if (resp.status.value !in 200..299) {+            error("start-upload HTTP ${resp.status.value}")+        }+        val uploadUrl = resp.headers["x-goog-upload-url"]+            ?: error("start-upload: missing x-goog-upload-url")+        return StartedUpload(+            uploadUrl = uploadUrl,+            chunkGranularity = resp.headers["x-goog-upload-chunk-granularity"]?.toLongOrNull() ?: 0L,+            mime = mime,+            encrypted = encrypted,+        )+    }++    /** POST the encrypted bytes to the resumable URL and decode the response. */+    private suspend fun finalizeUpload(start: StartedUpload): FinalizedUpload {+        val resp: HttpResponse = http.request(start.uploadUrl) {+            method = HttpMethod.Post+            uploadHeaders(+                contentLength = start.encrypted.size.toString(),+                command = "upload, finalize",+                offset = "0",+                contentMime = start.mime,+                protocol = null,+            )+            setBody(start.encrypted)+        }+        if (resp.status.value !in 200..299) {+            error("finalize-upload HTTP ${resp.status.value}")+        }+        var bodyBytes = resp.bodyAsBytes()+        // Sometimes the response is base64-encoded protobuf, sometimes+        // raw protobuf. Detect by attempting standard base64 parsing.+        if (isLikelyBase64(bodyBytes)) {+            bodyBytes = runCatching {+                Base64.decode(bodyBytes, Base64.NO_WRAP)+            }.getOrDefault(bodyBytes)+        }+        val parsed = UploadMediaResponse.parseFrom(bodyBytes)+        return FinalizedUpload(+            mediaID = parsed.media.mediaID,+            mediaNumber = parsed.media.mediaNumber,+        )+    }++    private fun isLikelyBase64(b: ByteArray): Boolean {+        if (b.isEmpty() || b.size % 4 != 0) return false+        return b.all { c ->+            val ch = c.toInt() and 0xFF+            (ch in 'A'.code..'Z'.code) || (ch in 'a'.code..'z'.code) ||+                (ch in '0'.code..'9'.code) || ch == '+'.code || ch == '/'.code || ch == '='.code+        }+    }++    /**+     * Apply the upload header bundle (port of util/func.go.NewMediaUploadHeaders).+     * The relay's anti-abuse layer inspects these alongside the URL ++     * Origin to decide whether the request looks like a real browser.+     */+    private fun io.ktor.client.request.HttpRequestBuilder.uploadHeaders(+        contentLength: String,+        command: String?,+        offset: String?,+        contentMime: String?,+        protocol: String?,+    ) {+        headers {+            append("sec-ch-ua", Endpoints.SecUA)+            if (protocol != null) append("x-goog-upload-protocol", protocol)+            append("x-goog-upload-header-content-length", contentLength)+            append("sec-ch-ua-mobile", Endpoints.SecUAMobile)+            append("user-agent", Endpoints.UserAgent)+            if (contentMime != null) append("x-goog-upload-header-content-type", contentMime)+            if (command != null) append("x-goog-upload-command", command)+            if (offset != null) append("x-goog-upload-offset", offset)+            append("sec-ch-ua-platform", "\"${Endpoints.UAPlatform}\"")+            append("accept", "*/*")+            append("origin", "https://messages.google.com")+            append("sec-fetch-site", "cross-site")+            append("sec-fetch-mode", "cors")+            append("sec-fetch-dest", "empty")+            append("referer", "https://messages.google.com/")+            append("accept-language", "en-US,en;q=0.9")+        }+    }++    /**+     * MIME-string → wire-enum mapping. Mirrors libgm's `MimeToMediaType`+     * map; only the formats we'll plausibly emit from the Compose+     * picker are listed. Falls back to the *_UNSPECIFIED bucket for the+     * top-level type so the relay still accepts the upload.+     */+    private fun mimeToFormat(mime: String): MediaFormats = when (mime.lowercase()) {+        "image/jpeg" -> MediaFormats.IMAGE_JPEG+        "image/jpg" -> MediaFormats.IMAGE_JPG+        "image/png" -> MediaFormats.IMAGE_PNG+        "image/gif" -> MediaFormats.IMAGE_GIF+        "image/wbmp" -> MediaFormats.IMAGE_WBMP+        "image/bmp", "image/x-ms-bmp" -> MediaFormats.IMAGE_X_MS_BMP+        "video/mp4" -> MediaFormats.VIDEO_MP4+        "video/3gpp" -> MediaFormats.VIDEO_3GPP+        "video/3gpp2" -> MediaFormats.VIDEO_3G2+        "video/webm" -> MediaFormats.VIDEO_WEBM+        "video/x-matroska" -> MediaFormats.VIDEO_MKV+        "audio/aac" -> MediaFormats.AUDIO_AAC+        "audio/mp4" -> MediaFormats.AUDIO_MP4+        "audio/mpeg" -> MediaFormats.AUDIO_MPEG+        "audio/ogg" -> MediaFormats.AUDIO_OGG+        else -> when (mime.substringBefore('/').lowercase()) {+            "image" -> MediaFormats.IMAGE_UNSPECIFIED+            "video" -> MediaFormats.VIDEO_UNSPECIFIED+            "audio" -> MediaFormats.AUDIO_UNSPECIFIED+            else -> MediaFormats.APP_UNSPECIFIED+        }+    }++    private data class StartedUpload(+        val uploadUrl: String,+        val chunkGranularity: Long,+        val mime: String,+        val encrypted: ByteArray,+    )++    private data class FinalizedUpload(+        val mediaID: String,+        val mediaNumber: Long,+    )++    companion object {+        private const val TAG = "GMessages/Media"+    }+}
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 a1f1fca889..c43e66abab 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt@@ -137,6 +137,165 @@ object GVoiceClient {         kickoffBackfill()     } +    /**+     * Send an SMS via Google Voice on the given thread.+     *+     * Mirrors `Client.SendMessage` in+     * `/Users/vayun/Documents/gvoice/pkg/libgv/client.go`: builds a+     * [Requests.ReqSendSMS] with a random transaction ID and the+     * bridge's `"!"` tracking-data fallback (the real signature is+     * generated by an Electron-hosted JS blob in the bridge; the+     * server happily accepts the placeholder for text-only sends).+     *+     * Returns true if the server responded 2xx with a thread item ID.+     */+    suspend fun sendMessage(conversationId: String, body: String): Boolean {+        if (_state.value !is State.Connected) return false+        val client = rpc ?: return false+        val webId = conversationId.substringAfter(':', conversationId)+        val req = baseSendBuilder(webId)+            .setText(body)+            .build()+        return doSend(client, webId, req)+    }++    /**+     * Send an MMS via Google Voice. The bridge inlines the media bytes+     * directly into `ReqSendSMS.Media` (see `handlematrix.go:91`); no+     * separate upload endpoint is required. Caption (if any) goes in+     * the text field — that matches what google-voice's own web client+     * does when sending photo + caption together.+     *+     * Only the explicit image MIME types listed in `ReqSendSMS.Media.Type`+     * are accepted: jpeg/png/gif/bmp/tiff/webp. Everything else returns+     * false (the server would reject it).+     */+    suspend fun sendMedia(+        conversationId: String,+        data: ByteArray,+        mime: String,+        caption: String?,+    ): Boolean {+        if (_state.value !is State.Connected) return false+        val client = rpc ?: return false+        val webId = conversationId.substringAfter(':', conversationId)+        val mediaType = mimeToVoiceMediaType(mime) ?: run {+            Log.w(TAG, "sendMedia: unsupported MIME $mime")+            return false+        }+        val media = Requests.ReqSendSMS.Media.newBuilder()+            .setType(mediaType)+            .setData(com.google.protobuf.ByteString.copyFrom(data))+            .build()+        val req = baseSendBuilder(webId)+            .apply { caption?.takeIf { it.isNotBlank() }?.let { setText(it) } }+            .setMedia(media)+            .build()+        return doSend(client, webId, req)+    }++    /**+     * Mark every message in [conversationId] as read via+     * `thread/updateattributes`. Mirrors `Client.UpdateThreadAttributes`+     * in `pkg/libgv/client.go` with `Read=true`.+     */+    suspend fun markRead(conversationId: String): Boolean {+        if (_state.value !is State.Connected) return false+        val client = rpc ?: return false+        val webId = conversationId.substringAfter(':', conversationId)+        val req = Requests.ReqUpdateAttributes.newBuilder()+            .setAttributes(+                Threads.ThreadAttributes.newBuilder()+                    .setThreadID(webId)+                    .setRead(true)+            )+            .setOtherAttributes(+                Threads.ThreadAttributes.newBuilder().setRead(true)+            )+            .setUnknownInt(1)+            .build()+        return try {+            client.postPbLite(+                url = VoiceEndpoints.EndpointUpdateAttributes,+                body = req,+                responseTemplate = Responses.RespUpdateAttributes.getDefaultInstance(),+            )+            true+        } catch (t: Throwable) {+            Log.w(TAG, "markRead failed thread=$webId: ${t.message}")+            false+        }+    }++    /**+     * Delete a Voice thread server-side. Mirrors `Client.DeleteThread`.+     * The realtime channel will (eventually) push a thread-list update+     * removing the thread; we also eagerly delete the local Room rows+     * from the session manager so the UI updates immediately.+     */+    suspend fun deleteThread(conversationId: String): Boolean {+        if (_state.value !is State.Connected) return false+        val client = rpc ?: return false+        val webId = conversationId.substringAfter(':', conversationId)+        val req = Requests.ReqDeleteThread.newBuilder()+            .setThreadID(webId)+            .build()+        return try {+            client.postPbLite(+                url = VoiceEndpoints.EndpointDeleteThread,+                body = req,+                responseTemplate = Responses.RespDeleteThread.getDefaultInstance(),+            )+            true+        } catch (t: Throwable) {+            Log.w(TAG, "deleteThread failed thread=$webId: ${t.message}")+            false+        }+    }++    /** Common builder: txn ID + bridge's tracking-data placeholder. */+    private fun baseSendBuilder(webId: String): Requests.ReqSendSMS.Builder =+        Requests.ReqSendSMS.newBuilder()+            .setThreadID(webId)+            .setTransactionID(+                Requests.ReqSendSMS.WrappedTxnID.newBuilder()+                    .setID(kotlin.random.Random.nextLong(100_000_000_000_000L))+                    .build()+            )+            .setTrackingData(+                Requests.ReqSendSMS.TrackingData.newBuilder()+                    .setData("!")+                    .build()+            )++    private suspend fun doSend(+        client: GVoiceRpcClient,+        webId: String,+        req: Requests.ReqSendSMS,+    ): Boolean = try {+        val resp = client.postPbLite(+            url = VoiceEndpoints.EndpointSendSms,+            body = req,+            responseTemplate = Responses.RespSendSMS.getDefaultInstance(),+        )+        Log.i(TAG, "sendsms ok thread=$webId itemId=${resp.threadItemID}")+        resp.threadItemID.isNotBlank()+    } catch (t: Throwable) {+        Log.w(TAG, "sendsms failed thread=$webId: ${t.message}")+        false+    }++    private fun mimeToVoiceMediaType(mime: String): Requests.ReqSendSMS.Media.Type? =+        when (mime.lowercase()) {+            "image/jpeg", "image/jpg" -> Requests.ReqSendSMS.Media.Type.JPEG+            "image/png" -> Requests.ReqSendSMS.Media.Type.PNG+            "image/gif" -> Requests.ReqSendSMS.Media.Type.GIF+            "image/bmp", "image/x-ms-bmp" -> Requests.ReqSendSMS.Media.Type.BMP+            "image/tiff" -> Requests.ReqSendSMS.Media.Type.TIFF+            "image/webp" -> Requests.ReqSendSMS.Media.Type.WEBP+            else -> null+        }+     /** 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/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 e0b45d2fa5..2d338187fd 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt@@ -1,5 +1,8 @@ package com.vayunmathur.messages.ui +import android.net.Uri+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box@@ -17,6 +20,8 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.combinedClickable+import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider@@ -26,8 +31,10 @@ import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text+import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults+import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -52,10 +59,12 @@ import com.vayunmathur.messages.Route import com.vayunmathur.messages.data.Conversation import com.vayunmathur.messages.data.Message import com.vayunmathur.messages.data.MessageDirection+import com.vayunmathur.messages.data.MessageSource import com.vayunmathur.messages.data.MessageState import com.vayunmathur.messages.data.MessagesDatabase import com.vayunmathur.messages.data.Reaction import com.vayunmathur.messages.util.MessagesViewModel+import com.vayunmathur.messages.util.ReactionAction import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.Json import java.text.DateFormat@@ -64,7 +73,7 @@ import java.util.Calendar import java.util.Date import java.util.Locale -@OptIn(ExperimentalMaterial3Api::class)+@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable fun ConversationScreen(     backStack: NavBackStack<Route>,@@ -83,6 +92,26 @@ fun ConversationScreen(      var draft by remember { mutableStateOf("") }     var sending by remember { mutableStateOf(false) }+    var reactingTo by remember { mutableStateOf<Message?>(null) }++    // Compose's PickVisualMedia uses the Android system photo picker+    // (Photos / Files on the user's device) — no READ_EXTERNAL_STORAGE+    // permission needed because the result is a tightly-scoped grant.+    val pickImage = rememberLauncherForActivityResult(+        contract = ActivityResultContracts.PickVisualMedia(),+    ) { uri: Uri? ->+        if (uri != null) {+            sending = true+            vm.sendMedia(+                conversationId = conversationId,+                uri = uri,+                caption = draft.trim().takeIf { it.isNotEmpty() },+            ) { _ ->+                sending = false+                draft = ""+            }+        }+    }      val listState = rememberLazyListState() @@ -117,7 +146,15 @@ fun ConversationScreen(         bottomBar = {             ComposeRow(                 draft = draft,-                onDraftChange = { draft = it },+                onDraftChange = { newDraft ->+                    draft = newDraft+                    // Fire a typing notification on each edit (gmessages+                    // only — voice has no typing endpoint). Cheap: it's+                    // a fire-and-forget on a coroutine.+                    if (conversation?.source == MessageSource.MESSAGES_WEB) {+                        vm.sendTyping(conversationId)+                    }+                },                 sending = sending,                 onSend = {                     val toSend = draft.trim()@@ -126,6 +163,13 @@ fun ConversationScreen(                     vm.send(conversationId, toSend) { _ -> sending = false }                     draft = ""                 },+                onAttach = {+                    pickImage.launch(+                        androidx.activity.result.PickVisualMediaRequest(+                            ActivityResultContracts.PickVisualMedia.ImageOnly+                        )+                    )+                },             )         },     ) { padding ->@@ -155,6 +199,7 @@ fun ConversationScreen(             // we feed it the chronological list REVERSED: newest first.             val items = remember(messages) { buildItems(messages).asReversed() }             val isGroup = conversation?.isGroup == true+            val canReact = conversation?.source == MessageSource.MESSAGES_WEB             LazyColumn(                 state = listState,                 reverseLayout = true,@@ -175,6 +220,9 @@ fun ConversationScreen(                                 showSender = isGroup && item.showSender,                                 isFirstInRun = item.isFirstInRun,                                 isLastInRun = item.isLastInRun,+                                onLongPress = if (canReact) {+                                    { reactingTo = item.message }+                                } else null,                             )                         }                     }@@ -182,6 +230,20 @@ fun ConversationScreen(             }         }     }++    // Long-press picker for reactions (gmessages only). Tapping an+    // emoji fires SEND_REACTION (ADD). The relay echoes the result+    // through MESSAGE_UPDATES which arrives via the long-poll and+    // re-renders the message bubble with the new reactionsJson.+    reactingTo?.let { target ->+        ReactionPickerDialog(+            onPick = { emoji ->+                vm.sendReaction(target.id, emoji, ReactionAction.ADD)+                reactingTo = null+            },+            onDismiss = { reactingTo = null },+        )+    } }  /** Render units we feed to LazyColumn. */@@ -255,12 +317,14 @@ private fun DayDivider(label: String) {     } } +@OptIn(ExperimentalFoundationApi::class) @Composable private fun MessageBubble(     msg: Message,     showSender: Boolean,     isFirstInRun: Boolean,     isLastInRun: Boolean,+    onLongPress: (() -> Unit)? = null, ) {     val isOutgoing = msg.direction == MessageDirection.OUTGOING     val bubbleColor = if (isOutgoing) MaterialTheme.colorScheme.primary@@ -299,7 +363,15 @@ private fun MessageBubble(             shape = shape,             modifier = Modifier                 .widthIn(max = 320.dp)-                .heightIn(min = 32.dp),+                .heightIn(min = 32.dp)+                .let { mod ->+                    if (onLongPress != null) {+                        mod.combinedClickable(+                            onClick = {},+                            onLongClick = onLongPress,+                        )+                    } else mod+                },         ) {             Text(                 msg.body,@@ -338,6 +410,40 @@ private fun MessageBubble(     } } +/**+ * Minimal reaction picker. The seven emoji shown match Google Messages'+ * built-in reaction palette (LIKE / LOVE / LAUGH / SURPRISED / SAD /+ * ANGRY / DISLIKE) but we send them as raw unicode — the relay+ * normalizes to the EmojiType enum server-side.+ */+@Composable+private fun ReactionPickerDialog(+    onPick: (String) -> Unit,+    onDismiss: () -> Unit,+) {+    val emojis = listOf("\uD83D\uDC4D", "\u2764\uFE0F", "\uD83D\uDE02", "\uD83D\uDE2E", "\uD83D\uDE22", "\uD83D\uDE21", "\uD83D\uDC4E")+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text("React") },+        text = {+            Row(+                modifier = Modifier.fillMaxWidth(),+                horizontalArrangement = Arrangement.SpaceEvenly,+            ) {+                emojis.forEach { e ->+                    TextButton(onClick = { onPick(e) }) {+                        Text(e, fontSize = 22.sp)+                    }+                }+            }+        },+        confirmButton = {},+        dismissButton = {+            TextButton(onClick = onDismiss) { Text("Cancel") }+        },+    )+}+ @Composable private fun ReactionsRow(json: String?, alignToEnd: Boolean) {     if (json.isNullOrBlank()) return@@ -421,6 +527,7 @@ private fun ComposeRow(     onDraftChange: (String) -> Unit,     sending: Boolean,     onSend: () -> Unit,+    onAttach: () -> Unit, ) {     Surface(         tonalElevation = 2.dp,@@ -432,6 +539,14 @@ private fun ComposeRow(                 .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,
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 f5851b257d..34002eeb04 100644--- a/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt+++ b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt@@ -2,6 +2,7 @@ package com.vayunmathur.messages.ui  import androidx.compose.foundation.background as foundationBackground import androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -32,6 +33,9 @@ import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState 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.draw.clip@@ -64,7 +68,7 @@ import java.util.Date  * When a source isn't connected (no pairing / no login), a "setup" card  * shows above the list inviting the user to complete the flow.  */-@OptIn(ExperimentalMaterial3Api::class)+@OptIn(ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable fun InboxScreen(     backStack: NavBackStack<Route>,@@ -73,6 +77,7 @@ fun InboxScreen( ) {     val conversations by db.conversationDao().observeAll().collectAsState(initial = emptyList())     val connectionStates by vm.connectionStates.collectAsState()+    var pendingDelete by remember { mutableStateOf<Conversation?>(null) }      Scaffold(         topBar = {@@ -111,6 +116,7 @@ fun InboxScreen(                         ConversationRow(                             conversation = conv,                             onClick = { backStack.add(Route.Conversation(conv.id)) },+                            onLongPress = { pendingDelete = conv },                         )                         HorizontalDivider(Modifier.padding(horizontal = 16.dp))                     }@@ -118,6 +124,30 @@ fun InboxScreen(             }         }     }++    pendingDelete?.let { conv ->+        androidx.compose.material3.AlertDialog(+            onDismissRequest = { pendingDelete = null },+            title = { Text("Delete conversation?") },+            text = {+                Text(+                    "This deletes the chat for ${conv.peerName ?: "this contact"} on your phone too. " ++                        "Existing messages can't be recovered.",+                )+            },+            confirmButton = {+                androidx.compose.material3.TextButton(onClick = {+                    vm.deleteConversation(conv.id)+                    pendingDelete = null+                }) { Text("Delete") }+            },+            dismissButton = {+                androidx.compose.material3.TextButton(onClick = { pendingDelete = null }) {+                    Text("Cancel")+                }+            },+        )+    } }  /** Shows source-specific setup cards at the top of the inbox when@@ -183,10 +213,12 @@ private fun SetupCard(     } } +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable private fun ConversationRow(     conversation: Conversation,     onClick: () -> Unit,+    onLongPress: () -> Unit = {}, ) {     ListItem(         headlineContent = {@@ -220,7 +252,10 @@ private fun ConversationRow(             }         },         leadingContent = { Avatar(conversation.peerName, conversation.avatarUrl, conversation.isGroup) },-        modifier = Modifier.clickable(onClick = onClick),+        modifier = Modifier.combinedClickable(+            onClick = onClick,+            onLongClick = onLongPress,+        ),         colors = ListItemDefaults.colors(containerColor = Color.Transparent),     ) }
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 340442fec2..d9fb9fa6e6 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt@@ -22,6 +22,7 @@ import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicBoolean @@ -120,10 +121,57 @@ object MessagesSessionManager {         )         val ok = when (source) {             MessageSource.MESSAGES_WEB -> GMessagesClient.sendMessage(conversationId, body)-            // Voice send isn't wired up yet — same stub-and-FAIL path-            // the gmessages send had before the SendMessageRequest-            // builder existed.-            MessageSource.VOICE -> false+            MessageSource.VOICE -> GVoiceClient.sendMessage(conversationId, body)+        }+        db.messageDao().updateState(+            pendingId,+            if (ok) MessageState.SENT else MessageState.FAILED,+        )+        return ok+    }++    /**+     * Send an image (or other supported media) on [conversationId].+     * Inserts a PENDING row carrying [caption] (or "[Image]" if blank)+     * so the UI gets immediate feedback, then routes the actual upload+     * to the per-source client.+     */+    suspend fun sendMedia(+        conversationId: String,+        bytes: ByteArray,+        mime: String,+        fileName: String,+        caption: String?,+    ): Boolean {+        val source = sourceFor(conversationId) ?: return false+        val previewBody = caption?.takeIf { it.isNotBlank() } ?: "[Image]"+        val pendingId = "${source.idPrefix}:pending:${System.currentTimeMillis()}"+        val now = System.currentTimeMillis()+        db.messageDao().upsert(+            Message(+                id = pendingId,+                conversationId = conversationId,+                body = previewBody,+                direction = MessageDirection.OUTGOING,+                state = MessageState.PENDING,+                timestamp = now,+                senderName = null,+            )+        )+        val ok = when (source) {+            MessageSource.MESSAGES_WEB -> GMessagesClient.sendMedia(+                conversationId = conversationId,+                data = bytes,+                mime = mime,+                fileName = fileName,+                caption = caption,+            )+            MessageSource.VOICE -> GVoiceClient.sendMedia(+                conversationId = conversationId,+                data = bytes,+                mime = mime,+                caption = caption,+            )         }         db.messageDao().updateState(             pendingId,@@ -133,7 +181,83 @@ object MessagesSessionManager {     }      suspend fun markRead(conversationId: String) {+        // Always update the local row immediately so the unread badge clears.         db.conversationDao().markRead(conversationId)+        // Then propagate to the server. Failures are non-fatal — the+        // local state already reflects "user has seen this".+        val source = sourceFor(conversationId) ?: return+        when (source) {+            MessageSource.MESSAGES_WEB -> {+                // gmessages MarkRead is per-message; pick the newest+                // message in the thread (same convention Messages-for-+                // Web uses when the user opens a chat).+                val latest = db.messageDao().observeForConversation(conversationId)+                    .firstOrNull()+                    ?.maxByOrNull { it.timestamp }+                val webMsgId = latest?.id?.substringAfter(':', latest.id)+                GMessagesClient.markRead(conversationId, webMsgId)+            }+            MessageSource.VOICE -> {+                GVoiceClient.markRead(conversationId)+            }+        }+    }++    /**+     * Delete [conversationId] on the server. The local row is removed+     * (and cascades clear its messages) once the per-source client+     * confirms — partial deletes leave the row in place so the user+     * can retry from the UI.+     */+    suspend fun deleteConversation(conversationId: String): Boolean {+        val source = sourceFor(conversationId) ?: return false+        val existing = db.conversationDao().get(conversationId)+        val ok = when (source) {+            MessageSource.MESSAGES_WEB -> {+                GMessagesClient.deleteConversation(conversationId, existing?.peerPhoneE164)+            }+            MessageSource.VOICE -> {+                GVoiceClient.deleteThread(conversationId)+            }+        }+        if (ok) db.conversationDao().deleteById(conversationId)+        return ok+    }++    /**+     * Add/remove/switch a reaction on a message. Only Google Messages+     * supports reactions — Voice ignores the call and returns false.+     */+    suspend fun sendReaction(messageId: String, emoji: String, action: ReactionAction): Boolean {+        val msg = db.messageDao().get(messageId) ?: return false+        val source = sourceFor(msg.conversationId) ?: return false+        return when (source) {+            MessageSource.MESSAGES_WEB -> GMessagesClient.sendReaction(+                messageId = messageId,+                emoji = emoji,+                action = when (action) {+                    ReactionAction.ADD ->+                        client.Client.SendReactionRequest.Action.ADD+                    ReactionAction.REMOVE ->+                        client.Client.SendReactionRequest.Action.REMOVE+                    ReactionAction.SWITCH ->+                        client.Client.SendReactionRequest.Action.SWITCH+                },+            )+            MessageSource.VOICE -> false+        }+    }++    /**+     * Notify the peer that the local user is typing.+     * Only Google Messages exposes a typing endpoint; Voice has none.+     */+    suspend fun sendTyping(conversationId: String): Boolean {+        val source = sourceFor(conversationId) ?: return false+        return when (source) {+            MessageSource.MESSAGES_WEB -> GMessagesClient.sendTyping(conversationId)+            MessageSource.VOICE -> false+        }     }      /**@@ -201,6 +325,7 @@ object MessagesSessionManager {                     isGroup = event.isGroup,                     participantCount = event.participantCount,                     conversationType = event.conversationType,+                    outgoingId = event.outgoingId ?: existing?.outgoingId,                 )                 db.conversationDao().upsert(merged)                 backfillComplete[event.source] = true@@ -239,6 +364,12 @@ object MessagesSessionManager {                     )                 )             }+            is GMEvent.MessageDeleted -> {+                db.messageDao().deleteById("${event.source.idPrefix}:${event.messageId}")+            }+            is GMEvent.ConversationDeleted -> {+                db.conversationDao().deleteById("${event.source.idPrefix}:${event.conversationId}")+            }         }     } @@ -248,3 +379,8 @@ object MessagesSessionManager {         else -> null     } }++/** 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 }
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 86692dcfc2..68bbcb0a2a 100644--- a/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt+++ b/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt@@ -36,6 +36,59 @@ class MessagesViewModel(application: Application) : AndroidViewModel(application         }     } +    /**+     * Send an image (or other supported media) on [conversationId].+     * The UI reads the URI into a byte array on the IO dispatcher (so+     * we don't block the main thread on large attachments); the actual+     * upload + send happens in the session manager.+     */+    fun sendMedia(+        conversationId: String,+        uri: android.net.Uri,+        caption: String?,+        onResult: (Boolean) -> Unit = {},+    ) {+        viewModelScope.launch {+            val (bytes, mime, fileName) = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+                val cr = getApplication<Application>().contentResolver+                val data = cr.openInputStream(uri)?.use { it.readBytes() }+                val type = cr.getType(uri) ?: "application/octet-stream"+                val name = uri.lastPathSegment ?: "attachment"+                Triple(data, type, name)+            }+            if (bytes == null) {+                onResult(false)+                return@launch+            }+            val ok = MessagesSessionManager.sendMedia(+                conversationId = conversationId,+                bytes = bytes,+                mime = mime,+                fileName = fileName,+                caption = caption,+            )+            onResult(ok)+        }+    }++    fun sendReaction(messageId: String, emoji: String, action: ReactionAction) {+        viewModelScope.launch {+            MessagesSessionManager.sendReaction(messageId, emoji, action)+        }+    }++    fun deleteConversation(conversationId: String, onResult: (Boolean) -> Unit = {}) {+        viewModelScope.launch {+            onResult(MessagesSessionManager.deleteConversation(conversationId))+        }+    }++    fun sendTyping(conversationId: String) {+        viewModelScope.launch {+            MessagesSessionManager.sendTyping(conversationId)+        }+    }+     fun fetchMessages(conversationId: String) {         MessagesSessionManager.fetchMessages(conversationId)     }