Modern Apps git

← Modern-Apps.git

messages: new app

Commit
88e90e63ca0087c85e973a9986cf3a0a63c5de38
Author
Vayun Mathur <[email protected]>
When
2026-05-30 16:37 UTC (6 months ago)
Parents
3432fd0

Diff

messages/build.gradle.kts
diff --git a/messages/build.gradle.kts b/messages/build.gradle.ktsnew file mode 100644index 0000000000..938f5affe0--- /dev/null+++ b/messages/build.gradle.kts@@ -0,0 +1,153 @@+import java.util.Locale+import javax.inject.Inject+import org.gradle.api.DefaultTask+import org.gradle.api.file.DirectoryProperty+import org.gradle.api.file.RegularFileProperty+import org.gradle.api.tasks.InputDirectory+import org.gradle.api.tasks.InputFile+import org.gradle.api.tasks.OutputDirectory+import org.gradle.api.tasks.TaskAction+import org.gradle.process.ExecOperations++plugins {+    id("common-conventions-app")+    id("com.google.devtools.ksp")+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.messages"+    }+}++// ----------------------------------------------------------------+// Protobuf code generation (manual)+// ----------------------------------------------------------------+//+// Both `com.squareup.wire` and `com.google.protobuf` Gradle plugins fail+// to apply to this module because they try to cast AGP 9's+// `ApplicationExtensionImpl` to the legacy `BaseExtension`, which AGP 9+// removed. Until those plugins catch up, we resolve `protoc` from Maven+// Central and invoke it directly. The resulting Java classes (lite+// runtime) are added to the variant's Java sources via the AGP+// `androidComponents` extension below.++val protocVersion = "4.28.3"++val osClassifier: String = run {+    val osName = System.getProperty("os.name").lowercase(Locale.US)+    val arch = System.getProperty("os.arch").lowercase(Locale.US)+    val os = when {+        osName.contains("mac") || osName.contains("darwin") -> "osx"+        osName.contains("win") -> "windows"+        else -> "linux"+    }+    val cpu = when {+        arch.contains("aarch64") || arch.contains("arm64") -> "aarch_64"+        arch.contains("64") -> "x86_64"+        else -> "x86_32"+    }+    "$os-$cpu"+}++val protocConfig: Configuration = configurations.create("protocBinary") {+    isCanBeResolved = true+    isCanBeConsumed = false+}++dependencies {+    "protocBinary"("com.google.protobuf:protoc:$protocVersion:$osClassifier@exe")+}++val protoSrcDir = layout.projectDirectory.dir("src/main/proto")+val protoGenDir = layout.buildDirectory.dir("generated/source/proto/java")++// Custom task class so we can inject ExecOperations cleanly (the+// configuration cache rejects capturing the Project at execution time).+abstract class GenerateProtoTask @Inject constructor(+    private val exec: ExecOperations,+) : DefaultTask() {+    @get:InputFile+    abstract val protocBinary: RegularFileProperty++    @get:InputDirectory+    abstract val protoSourceDir: DirectoryProperty++    @get:OutputDirectory+    abstract val outputDir: DirectoryProperty++    @TaskAction+    fun run() {+        val binary = protocBinary.get().asFile+        binary.setExecutable(true)+        val out = outputDir.get().asFile+        out.deleteRecursively()+        out.mkdirs()+        val srcDir = protoSourceDir.get().asFile+        val protoFiles = srcDir.walkTopDown()+            .filter { it.isFile && it.extension == "proto" }+            .toList()+        if (protoFiles.isEmpty()) return+        exec.exec {+            commandLine = buildList {+                add(binary.absolutePath)+                add("--java_out=${out.absolutePath}")+                add("-I=${srcDir.absolutePath}")+                addAll(protoFiles.map { it.absolutePath })+            }+        }+    }+}++val generateProto = tasks.register<GenerateProtoTask>("generateProto") {+    protocBinary.set(layout.file(protocConfig.elements.map { it.single().asFile }))+    protoSourceDir.set(protoSrcDir)+    outputDir.set(protoGenDir)+}++// Make Kotlin/Java/KSP compilation wait on protoc. KSP runs ahead of+// compileKotlin so it has to be in this list too.+tasks.matching {+    it.name.startsWith("compile") &&+        (it.name.endsWith("Kotlin") || it.name.endsWith("JavaWithJavac")) ||+    it.name.startsWith("ksp")+}.configureEach {+    dependsOn(generateProto)+}++androidComponents {+    onVariants { variant ->+        variant.sources.java?.addStaticSourceDirectory(protoGenDir.get().asFile.absolutePath)+    }+}++dependencies {+    // External Libraries+    implementation(libs.libphonenumber)++    // Room+    implementation(libs.androidx.room.runtime)+    implementation(libs.androidx.room.ktx)+    ksp(libs.androidx.room.compiler)++    // Protobuf runtime — full Java variant. The lite runtime drops the+    // reflection API which we need for the PB-Lite encoder.+    implementation(libs.protobuf.java)++    // ZXing core — QR code encoding only (no scanner UI). We render the+    // pairing QR ourselves in a native Compose composable.+    implementation(libs.zxing.core)++    // Ktor (transitive from :library:network is implementation-scoped+    // so we need to declare directly).+    implementation(libs.ktor.client.core)+    implementation(libs.ktor.client.cio)++    // Coil — loads device-contact photo URIs (content://) into the+    // conversation-row avatars in InboxScreen / ConversationScreen.+    implementation(libs.coil.compose)++    // Network — for any auxiliary HTTP we end up needing outside the+    // dedicated RPC client.+    implementation(project(":library:network"))+}
messages/src/main/AndroidManifest.xml
diff --git a/messages/src/main/AndroidManifest.xml b/messages/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..2739ebd629--- /dev/null+++ b/messages/src/main/AndroidManifest.xml@@ -0,0 +1,56 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <!-- Foreground service hosts the two long-lived WebViews so we keep+         receiving messages while the app is backgrounded. dataSync type is+         the right one — we're maintaining a long-lived data connection,+         not tracking location or playing media. -->+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />+    <!-- For showing incoming-message notifications on Android 13+. -->+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <!-- Re-start the sync service after device reboot. -->+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />+    <!-- For resolving inbound phone numbers to a contact name. -->+    <uses-permission android:name="android.permission.READ_CONTACTS" />++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <service+            android:name=".util.MessagesService"+            android:foregroundServiceType="dataSync"+            android:exported="false" />++        <receiver+            android:name=".util.MessagesQuickReplyReceiver"+            android:exported="false" />++        <receiver+            android:name=".util.BootReceiver"+            android:exported="true"+            android:enabled="true">+            <intent-filter>+                <action android:name="android.intent.action.BOOT_COMPLETED" />+            </intent-filter>+        </receiver>+    </application>++</manifest>
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.ktnew file mode 100644index 0000000000..aa129e7523--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt@@ -0,0 +1,86 @@+package com.vayunmathur.messages++import android.Manifest+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.remember+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.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.messages.data.buildMessagesDatabase+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.util.MessagesViewModel+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                // POST_NOTIFICATIONS is the only runtime perm we strictly+                // need — without it the foreground service runs but the+                // user sees no incoming-message alerts. READ_CONTACTS is+                // requested on-demand when the inbox actually tries to+                // resolve a phone number to a contact name.+                val perms = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                    arrayOf(+                        Manifest.permission.POST_NOTIFICATIONS,+                        // Used by ContactResolver to look up display names+                        // and photos for the conversation peers.+                        Manifest.permission.READ_CONTACTS,+                    )+                } else {+                    arrayOf(Manifest.permission.READ_CONTACTS)+                }+                PermissionsChecker(perms, getString(R.string.permissions_post_notifications)) {+                    val db = remember { buildMessagesDatabase(this@MainActivity) }+                    Navigation(db)+                }+            }+        }+    }+}++/** Navigation graph for the messages module. */+@Serializable+sealed interface Route : NavKey {+    @Serializable data object Inbox : Route+    @Serializable data class Conversation(val conversationId: String) : Route+    @Serializable data object Settings : Route+    @Serializable data object PairMessages : Route+}++@Composable+private fun Navigation(+    db: com.vayunmathur.messages.data.MessagesDatabase,+    vm: MessagesViewModel = viewModel(),+) {+    val backStack = rememberNavBackStack<Route>(Route.Inbox)+    MainNavigation(backStack) {+        entry<Route.Inbox>(metadata = ListPage { }) {+            InboxScreen(backStack, vm, db)+        }+        entry<Route.Conversation> {+            ConversationScreen(backStack, vm, db, it.conversationId)+        }+        entry<Route.Settings> {+            SettingsScreen(backStack, vm)+        }+        entry<Route.PairMessages> {+            MessagesPairingScreen(backStack, vm)+        }+    }+}
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.ktnew file mode 100644index 0000000000..832fdf80b1--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/data/Entities.kt@@ -0,0 +1,82 @@+package com.vayunmathur.messages.data++import androidx.room.ColumnInfo+import androidx.room.Entity+import androidx.room.ForeignKey+import androidx.room.Index+import androidx.room.PrimaryKey++/**+ * One conversation row.+ *+ * The [id] is a string with a source prefix so that two conversations from+ * different sources can't collide (e.g. "msgs:thread_42" vs "voice:thread_42").+ * The puppet sets the prefix; the data layer only stores it.+ */+@Entity(tableName = "conversations")+data class Conversation(+    @PrimaryKey val id: String,+    val source: MessageSource,+    /** Display name surfaced by the underlying web app. May be a phone+     *  number if the user has no contact stored for the peer. */+    val peerName: String?,+    /** E.164-normalized number for one-on-one chats; null for groups. */+    @ColumnInfo(name = "peer_phone_e164") val peerPhoneE164: String?,+    @ColumnInfo(name = "avatar_url") val avatarUrl: String?,+    @ColumnInfo(name = "last_preview") val lastMessagePreview: String?,+    /** Timestamp of the last message in the thread, epoch-ms. */+    @ColumnInfo(name = "last_ts") val lastMessageTimestamp: Long,+    @ColumnInfo(name = "unread_count") val unreadCount: Int,+    /** Whether this thread has > 2 participants. Drives both the avatar+     *  treatment (group glyph vs single photo) and the row title format. */+    @ColumnInfo(name = "is_group") val isGroup: Boolean = false,+    /** Number of OTHER participants (i.e. excluding the local user). */+    @ColumnInfo(name = "participant_count") val participantCount: Int = 0,+    /** 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,+)++/**+ * One message row.+ *+ * [id] is also source-prefixed because the underlying web apps assign+ * their own per-thread numeric ids that aren't unique across sources.+ */+@Entity(+    tableName = "messages",+    foreignKeys = [+        ForeignKey(+            entity = Conversation::class,+            parentColumns = ["id"],+            childColumns = ["conversation_id"],+            onDelete = ForeignKey.CASCADE,+        ),+    ],+    indices = [Index("conversation_id"), Index("timestamp")],+)+data class Message(+    @PrimaryKey val id: String,+    @ColumnInfo(name = "conversation_id") val conversationId: String,+    val body: String,+    val direction: MessageDirection,+    val state: MessageState,+    /** Epoch-ms. */+    @ColumnInfo(name = "timestamp") val timestamp: Long,+    /** Display name of the sender (mainly useful when group messages+     *  arrive — for direct messages this matches the conversation peer). */+    @ColumnInfo(name = "sender_name") val senderName: String?,+    /**+     * JSON-serialized list of [com.vayunmathur.messages.data.Reaction]+     * applied to this message (`[{"emoji":"❤️","count":2}, …]`). null+     * when none. Stored as a compact blob to avoid a second table for+     * what's effectively per-message metadata.+     */+    @ColumnInfo(name = "reactions_json") val reactionsJson: String? = null,+)++/** Aggregated reaction on a message. The relay surfaces these per-emoji+ *  with a participant list; we collapse to "emoji + count" because v1+ *  doesn't need to attribute the reaction to a specific participant. */[email protected]+data class Reaction(val emoji: String, val count: Int)
messages/src/main/java/com/vayunmathur/messages/data/MessageSource.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/data/MessageSource.kt b/messages/src/main/java/com/vayunmathur/messages/data/MessageSource.ktnew file mode 100644index 0000000000..143434cfe5--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/data/MessageSource.kt@@ -0,0 +1,34 @@+package com.vayunmathur.messages.data++/**+ * Where a conversation originated. Today there is only one source —+ * SMS conversations relayed through the user's phone via the+ * Google-Messages-for-Web pairing. The enum is preserved so we don't+ * need a Room schema migration if we later add another source (e.g.+ * Signal-Desktop-style pairing) and so source-prefixed primary keys+ * keep their semantics ("msgs:<id>").+ */+enum class MessageSource {+    MESSAGES_WEB;++    /** Prefix for compound primary keys (e.g. "msgs:<thread_id>"). */+    val idPrefix: String get() = when (this) {+        MESSAGES_WEB -> "msgs"+    }+}++/** Direction of a single [Message] relative to the local user. */+enum class MessageDirection { INCOMING, OUTGOING }++/**+ * Delivery state for an outgoing message. Inbound messages are always+ * stored with state = [DELIVERED].+ *+ * - [PENDING]   shown immediately when the user hits send, before the+ *               puppet WebView has confirmed the send went through.+ * - [SENT]      the web UI shows the message as accepted by the relay.+ * - [DELIVERED] the recipient's device acknowledged. Not all sources+ *               surface delivery receipts; treat absence as "stay at SENT".+ * - [FAILED]    sending failed; the row is kept so the user can retry.+ */+enum class MessageState { PENDING, SENT, DELIVERED, FAILED }
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.ktnew file mode 100644index 0000000000..7656ed1c04--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt@@ -0,0 +1,107 @@+package com.vayunmathur.messages.data++import androidx.room.Dao+import androidx.room.OnConflictStrategy+import androidx.room.Query+import androidx.room.TypeConverter+import androidx.room.TypeConverters+import androidx.room.Upsert+import kotlinx.coroutines.flow.Flow++@Dao+interface ConversationDao {+    @Upsert+    suspend fun upsert(conversation: Conversation)++    @Upsert+    suspend fun upsertAll(conversations: List<Conversation>)++    @Query("SELECT * FROM conversations ORDER BY last_ts DESC")+    fun observeAll(): Flow<List<Conversation>>++    @Query("SELECT * FROM conversations WHERE id = :id LIMIT 1")+    fun observe(id: String): Flow<Conversation?>++    @Query("SELECT * FROM conversations WHERE id = :id LIMIT 1")+    suspend fun get(id: String): Conversation?++    @Query("UPDATE conversations SET unread_count = 0 WHERE id = :id")+    suspend fun markRead(id: String)++    @Query("DELETE FROM conversations WHERE source = :source")+    suspend fun deleteAllForSource(source: MessageSource)+}++@Dao+interface MessageDao {+    @Upsert+    suspend fun upsert(message: Message)++    @Upsert+    suspend fun upsertAll(messages: List<Message>)++    @Query("SELECT * FROM messages WHERE conversation_id = :conversationId ORDER BY timestamp ASC")+    fun observeForConversation(conversationId: String): Flow<List<Message>>++    @Query("SELECT * FROM messages WHERE id = :id LIMIT 1")+    suspend fun get(id: String): Message?++    @Query("UPDATE messages SET state = :state WHERE id = :id")+    suspend fun updateState(id: String, state: MessageState)+}++/**+ * Room can store our enums as their `.name` strings via a single+ * generic-style converter pair. Keeps migrations stable if enum order+ * ever changes (don't store ordinal).+ */+class MessagesConverters {+    @TypeConverter+    fun fromSource(value: MessageSource): String = value.name+    @TypeConverter+    fun toSource(value: String): MessageSource = MessageSource.valueOf(value)++    @TypeConverter+    fun fromDirection(value: MessageDirection): String = value.name+    @TypeConverter+    fun toDirection(value: String): MessageDirection = MessageDirection.valueOf(value)++    @TypeConverter+    fun fromState(value: MessageState): String = value.name+    @TypeConverter+    fun toState(value: String): MessageState = MessageState.valueOf(value)+}+[email protected](+    entities = [Conversation::class, Message::class],+    version = 3,+    exportSchema = false,+)+@TypeConverters(MessagesConverters::class)+abstract class MessagesDatabase : androidx.room.RoomDatabase() {+    abstract fun conversationDao(): ConversationDao+    abstract fun messageDao(): MessageDao+}++private val dbLock = Any()+@Volatile private var sharedDb: MessagesDatabase? = null++/**+ * Returns the process-singleton [MessagesDatabase]. We must return the+ * same instance everywhere — Room's Flow change-notifications are+ * per-instance, so writes via one instance never notify Flows observed+ * via another, even when both point at the same SQLite file.+ */+fun buildMessagesDatabase(context: android.content.Context): MessagesDatabase {+    sharedDb?.let { return it }+    return synchronized(dbLock) {+        sharedDb ?: androidx.room.Room.databaseBuilder(+            context.applicationContext,+            MessagesDatabase::class.java,+            "messages.db",+        )+            .fallbackToDestructiveMigration(true)+            .build()+            .also { sharedDb = it }+    }+}
messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.ktnew file mode 100644index 0000000000..32481d74af--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt@@ -0,0 +1,118 @@+package com.vayunmathur.messages.gmessages++import android.content.Context+import android.util.Base64+import com.google.protobuf.ByteString+import com.vayunmathur.library.util.DataStoreUtils+import authentication.Authentication+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Persisted authentication state for a Google-Messages-for-Web session.+ *+ * Direct port of the `AuthData` struct in+ * `/Users/vayun/Documents/gmessages/pkg/libgm/client.go` — minus the+ * Google-account / GAIA pairing fields we don't support in v1.+ *+ * Lifecycle:+ *   - On first launch (no persisted blob), the [GMessagesClient] starts+ *     with [generateInitial] and persists after a successful pair.+ *   - On every change (post-pair, post-token-refresh), we re-serialize+ *     and write back via [save].+ *   - On app launch with a persisted blob, [load] reconstitutes the+ *     entire session so we don't have to re-pair.+ */+@Serializable+data class AuthData(+    /** AES + HMAC keys shared with the paired phone. Bodies are+     *  encrypted/decrypted with these on the wire. */+    val requestCrypto: AesCtrHmacBlob,++    /** Long-lived ECDSA P-256 key used to sign token-refresh requests. */+    val refreshKey: EcdsaP256Jwk,++    /** Tachyon auth token returned by RegisterPhoneRelay and refreshed+     *  periodically via Pairing/RefreshPhoneRelay. base64 of raw bytes. */+    val tachyonAuthTokenB64: String? = null,++    /** Epoch-ms when the tachyon token expires (TTL from the relay). */+    val tachyonExpiryMs: Long = 0L,++    /** TTL in microseconds (per the Tachyon RPC field convention). */+    val tachyonTtlUs: Long = 0L,++    /** Identity of the paired phone, as base64-encoded+     *  `authentication.Device` protobuf. Sent in every OutgoingRPCMessage+     *  so the relay knows which phone to push to. */+    val mobileDeviceB64: String? = null,++    /** Identity of THIS browser-side device (us). Returned by the relay+     *  after pairing completes. base64 of `authentication.Device` proto. */+    val browserDeviceB64: String? = null,++    /** Stable session ID used as the sessionID on every outgoing RPC.+     *  Regenerated on each fresh pair. */+    val sessionId: String,+) {++    fun isPaired(): Boolean = !tachyonAuthTokenB64.isNullOrBlank() && mobileDeviceB64 != null++    /** Decode the tachyon token back to raw bytes. */+    fun tachyonToken(): ByteArray? =+        tachyonAuthTokenB64?.let { Base64.decode(it, Base64.NO_WRAP) }++    /** Decode the paired phone's device proto. */+    fun mobile(): Authentication.Device? = mobileDeviceB64?.let {+        Authentication.Device.parseFrom(Base64.decode(it, Base64.NO_WRAP))+    }++    /** Decode the browser-side device proto. */+    fun browser(): Authentication.Device? = browserDeviceB64?.let {+        Authentication.Device.parseFrom(Base64.decode(it, Base64.NO_WRAP))+    }++    /** Materialize the AES helper from the persisted key blob. */+    fun crypto(): AesCtrHmac = AesCtrHmac(+        aesKey = Base64.decode(requestCrypto.aesKeyB64, Base64.NO_WRAP),+        hmacKey = Base64.decode(requestCrypto.hmacKeyB64, Base64.NO_WRAP),+    )++    suspend fun save(context: Context) {+        val json = Json.encodeToString(serializer(), this)+        DataStoreUtils.getInstance(context).setString(DATA_STORE_KEY, json)+    }++    companion object {+        private const val DATA_STORE_KEY = "gmessages_auth_data"++        /** Build a fresh auth state suitable for kicking off a new pair. */+        fun generateInitial(): AuthData {+            val aes = AesCtrHmac.generate()+            return AuthData(+                requestCrypto = AesCtrHmacBlob(+                    aesKeyB64 = Base64.encodeToString(aes.aesKey, Base64.NO_WRAP),+                    hmacKeyB64 = Base64.encodeToString(aes.hmacKey, Base64.NO_WRAP),+                ),+                refreshKey = EcdsaP256Jwk.generate(),+                sessionId = java.util.UUID.randomUUID().toString(),+            )+        }++        suspend fun load(context: Context): AuthData? {+            val json = DataStoreUtils.getInstance(context).getString(DATA_STORE_KEY) ?: return null+            if (json.isBlank()) return null+            return runCatching { Json.decodeFromString(serializer(), json) }.getOrNull()+        }+    }+}++/** AES + HMAC key pair serialized as base64 strings. */+@Serializable+data class AesCtrHmacBlob(+    val aesKeyB64: String,+    val hmacKeyB64: String,+)++/** Convenience extension: wrap raw bytes as a protobuf ByteString. */+fun ByteArray.toByteString(): ByteString = ByteString.copyFrom(this)
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.ktnew file mode 100644index 0000000000..924f4abda4--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Constants.kt@@ -0,0 +1,53 @@+package com.vayunmathur.messages.gmessages++/**+ * Endpoints + headers ported from+ * /Users/vayun/Documents/gmessages/pkg/libgm/util/{paths,constants,func}.go.+ *+ * All values are copied verbatim from the reference implementation —+ * Google's Messages-for-Web client uses the same constants. Bumping the+ * Chrome version periodically (it's part of the User-Agent + Sec-CH-UA)+ * is recommended to stay current with real Chrome releases.+ */+object Endpoints {+    const val GoogleApiKey = "AIzaSyCA4RsOZUFrm9whhtGosPlJLmVPnfSHKz8"+    const val UserAgent =+        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"+    const val SecUA = "\"Google Chrome\";v=\"146\", \"Chromium\";v=\"146\", \"Not-A.Brand\";v=\"24\""+    const val UAPlatform = "Linux"+    const val SecUAMobile = "?0"+    const val XUserAgent = "grpc-web-javascript/0.1"++    /** Base URL the QR code points at. Combined with a base64-encoded+     *  URLData protobuf to form the actual scanned URL. */+    const val QrCodeBaseUrl = "https://support.google.com/messages/?p=web_computer#?c="++    const val MessagesBaseUrl = "https://messages.google.com"+    const val GoogleAuthenticationUrl = "$MessagesBaseUrl/web/authentication"+    const val GoogleTimesourceUrl = "$MessagesBaseUrl/web/timesource"++    private const val ImBase = "https://instantmessaging-pa.googleapis.com"+    private const val ImBaseGoogle = "https://instantmessaging-pa.clients6.google.com"++    private const val PairingBase = "$ImBase/\$rpc/google.internal.communications.instantmessaging.v1.Pairing"+    const val RegisterPhoneRelayUrl = "$PairingBase/RegisterPhoneRelay"+    const val RefreshPhoneRelayUrl = "$PairingBase/RefreshPhoneRelay"+    const val GetWebEncryptionKeyUrl = "$PairingBase/GetWebEncryptionKey"+    const val RevokeRelayPairingUrl = "$PairingBase/RevokeRelayPairing"++    private const val MessagingBase = "$ImBase/\$rpc/google.internal.communications.instantmessaging.v1.Messaging"+    const val ReceiveMessagesUrl = "$MessagingBase/ReceiveMessages"+    const val SendMessageUrl = "$MessagingBase/SendMessage"+    const val AckMessagesUrl = "$MessagingBase/AckMessages"+}++/** MIME types for the two wire encodings the relay accepts. */+object ContentTypes {+    /** Native protobuf binary encoding — used for inbound long-poll+     *  payloads and Pairing/Receive paths. */+    const val Protobuf = "application/x-protobuf"++    /** Google's "PB-Lite" JSON-array encoding — used for some outbound+     *  paths including SendMessage. See [PbLite] for the codec. */+    const val PbLite = "application/json+protobuf"+}
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.ktnew file mode 100644index 0000000000..56b8f95759--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Crypto.kt@@ -0,0 +1,172 @@+package com.vayunmathur.messages.gmessages++import android.util.Base64+import java.math.BigInteger+import java.security.KeyFactory+import java.security.KeyPair+import java.security.KeyPairGenerator+import java.security.SecureRandom+import java.security.Signature+import java.security.interfaces.ECPrivateKey+import java.security.interfaces.ECPublicKey+import java.security.spec.ECGenParameterSpec+import java.security.spec.ECParameterSpec+import java.security.spec.ECPoint+import java.security.spec.ECPrivateKeySpec+import java.security.spec.ECPublicKeySpec+import javax.crypto.Cipher+import javax.crypto.Mac+import javax.crypto.spec.IvParameterSpec+import javax.crypto.spec.SecretKeySpec+import kotlinx.serialization.Serializable++/**+ * Direct port of `crypto/aesctr.go` from mautrix-gmessages.+ *+ * Wire format (output of [encrypt], input of [decrypt]):+ *     ciphertext || IV(16 bytes) || HMAC-SHA256(ciphertext||IV)(32 bytes)+ *+ * The AES key encrypts message bodies and is shared with the user's+ * phone via the QR pairing payload (see [PairFlow]). The HMAC key+ * authenticates the encrypted blob against tampering.+ */+class AesCtrHmac(+    val aesKey: ByteArray,+    val hmacKey: ByteArray,+) {++    fun encrypt(plaintext: ByteArray): ByteArray {+        val iv = ByteArray(AES_BLOCK_SIZE)+        SecureRandom().nextBytes(iv)+        val cipher = Cipher.getInstance("AES/CTR/NoPadding").apply {+            init(Cipher.ENCRYPT_MODE, SecretKeySpec(aesKey, "AES"), IvParameterSpec(iv))+        }+        val ct = cipher.doFinal(plaintext)+        val withIv = ct + iv+        val mac = Mac.getInstance("HmacSHA256").apply {+            init(SecretKeySpec(hmacKey, "HmacSHA256"))+        }+        val tag = mac.doFinal(withIv)+        return withIv + tag+    }++    fun decrypt(blob: ByteArray): ByteArray {+        require(blob.size >= 48) { "ciphertext blob too short: ${blob.size} < 48" }+        val tag = blob.copyOfRange(blob.size - HMAC_TAG_SIZE, blob.size)+        val withIv = blob.copyOfRange(0, blob.size - HMAC_TAG_SIZE)++        val mac = Mac.getInstance("HmacSHA256").apply {+            init(SecretKeySpec(hmacKey, "HmacSHA256"))+        }+        val expectedTag = mac.doFinal(withIv)+        require(tag.contentEquals(expectedTag)) { "HMAC mismatch" }++        val iv = withIv.copyOfRange(withIv.size - AES_BLOCK_SIZE, withIv.size)+        val ct = withIv.copyOfRange(0, withIv.size - AES_BLOCK_SIZE)+        val cipher = Cipher.getInstance("AES/CTR/NoPadding").apply {+            init(Cipher.DECRYPT_MODE, SecretKeySpec(aesKey, "AES"), IvParameterSpec(iv))+        }+        return cipher.doFinal(ct)+    }++    companion object {+        private const val AES_BLOCK_SIZE = 16+        private const val HMAC_TAG_SIZE = 32++        fun generate(): AesCtrHmac = AesCtrHmac(+            aesKey = generateKey(32),+            hmacKey = generateKey(32),+        )++        fun generateKey(length: Int): ByteArray {+            val bytes = ByteArray(length)+            SecureRandom().nextBytes(bytes)+            return bytes+        }+    }+}++/**+ * 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+ * representation could theoretically be cross-read, though we never need+ * to (each install regenerates its own key on first pair).+ *+ * The private scalar `d` and the public point `(x, y)` are stored as+ * base64url-without-padding-encoded big-endian byte sequences. This+ * matches RFC 7518 §6.2.2.+ */+@Serializable+data class EcdsaP256Jwk(+    val kty: String = "EC",+    val crv: String = "P-256",+    val d: String,+    val x: String,+    val y: String,+) {+    fun toKeyPair(): KeyPair {+        val params = ecParameterSpec()+        val dBig = BigInteger(1, decodeUrl(d))+        val xBig = BigInteger(1, decodeUrl(x))+        val yBig = BigInteger(1, decodeUrl(y))+        val pubSpec = ECPublicKeySpec(ECPoint(xBig, yBig), params)+        val privSpec = ECPrivateKeySpec(dBig, params)+        val kf = KeyFactory.getInstance("EC")+        return KeyPair(kf.generatePublic(pubSpec), kf.generatePrivate(privSpec))+    }++    /** DER-encoded SubjectPublicKeyInfo, the same shape `x509.MarshalPKIXPublicKey` produces in Go. */+    fun publicKeyDer(): ByteArray = toKeyPair().public.encoded++    fun sign(data: ByteArray): ByteArray {+        val priv = toKeyPair().private as ECPrivateKey+        return Signature.getInstance("SHA256withECDSA").apply {+            initSign(priv)+            update(data)+        }.sign()+    }++    companion object {+        fun generate(): EcdsaP256Jwk {+            val kpg = KeyPairGenerator.getInstance("EC").apply {+                initialize(ECGenParameterSpec("secp256r1"), SecureRandom())+            }+            val kp = kpg.generateKeyPair()+            val pub = kp.public as ECPublicKey+            val priv = kp.private as ECPrivateKey+            return EcdsaP256Jwk(+                d = encodeUrl(priv.s.toUnsignedFixedWidth(32)),+                x = encodeUrl(pub.w.affineX.toUnsignedFixedWidth(32)),+                y = encodeUrl(pub.w.affineY.toUnsignedFixedWidth(32)),+            )+        }++        private fun ecParameterSpec(): ECParameterSpec {+            // Bootstrap a key just to grab the curve parameters object.+            val kpg = KeyPairGenerator.getInstance("EC").apply {+                initialize(ECGenParameterSpec("secp256r1"))+            }+            return (kpg.generateKeyPair().public as ECPublicKey).params+        }++        private fun encodeUrl(bytes: ByteArray): String =+            Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)++        private fun decodeUrl(s: String): ByteArray =+            Base64.decode(s, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)+    }+}++/** Big-endian, fixed-width unsigned byte representation. Strips the+ *  BigInteger sign byte when present and left-pads with zeros to [width]. */+private fun BigInteger.toUnsignedFixedWidth(width: Int): ByteArray {+    val raw = toByteArray()+    val trimmed = if (raw.isNotEmpty() && raw[0] == 0.toByte() && raw.size > width) {+        raw.copyOfRange(1, raw.size)+    } else raw+    return if (trimmed.size >= width) {+        trimmed.copyOfRange(trimmed.size - width, trimmed.size)+    } else {+        ByteArray(width - trimmed.size) + trimmed+    }+}
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.ktnew file mode 100644index 0000000000..a16b3153ee--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/Events.kt@@ -0,0 +1,56 @@+package com.vayunmathur.messages.gmessages++import com.vayunmathur.messages.data.MessageSource++/**+ * Events emitted by [GMessagesClient] for the rest of the app to react to.+ * Shape preserved from the previous WebView-puppet design so the+ * repository / Room-write path is unchanged.+ *+ * The [conversationId] / [messageId] strings are the WEB-APP-INTERNAL ids+ * — Google's per-thread numeric ids. The data layer prefixes them with+ * the source name before persisting; see [MessageSource.idPrefix].+ */+sealed interface GMEvent {+    val source: MessageSource++    /** A conversation row's metadata changed. Fired on initial scan and+     *  on any subsequent change the long-poll surfaces. */+    data class ConversationUpdate(+        override val source: MessageSource,+        val conversationId: String,+        val peerName: String?,+        val peerPhone: String?,+        val avatarUrl: String?,+        val lastPreview: String?,+        val lastTimestamp: Long,+        val unreadCount: Int,+        val isGroup: Boolean = false,+        val participantCount: Int = 0,+        val conversationType: String? = null,+    ) : GMEvent++    /** A message row appeared / was updated. Used for backfill + live sync. */+    data class MessageUpdate(+        override val source: MessageSource,+        val conversationId: String,+        val messageId: String,+        val body: String,+        val outgoing: Boolean,+        val timestamp: Long,+        val senderName: String?,+        val reactionsJson: String? = null,+    ) : GMEvent++    /** A NEW inbound message just arrived. Distinct from MessageUpdate+     *  because it should fire a notification; MessageUpdate is just sync. */+    data class IncomingMessage(+        override val source: MessageSource,+        val conversationId: String,+        val messageId: String,+        val body: String,+        val peerName: String?,+        val peerPhone: String?,+        val timestamp: Long,+    ) : 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.ktnew file mode 100644index 0000000000..e5917c4907--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt@@ -0,0 +1,452 @@+package com.vayunmathur.messages.gmessages++import android.content.Context+import android.util.Log+import client.Client.ListConversationsRequest+import client.Client.ListConversationsResponse+import client.Client.ListMessagesRequest+import client.Client.ListMessagesResponse+import com.vayunmathur.messages.data.MessageSource+import com.vayunmathur.messages.util.ContactResolver+import conversations.Conversations.Conversation+import conversations.Conversations.Message+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import rpc.Rpc.ActionType+import rpc.Rpc.MessageType+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Process-global owner of the Google-Messages-for-Web protocol session.+ *+ * Lifecycle:+ *  1. [init] is called once by the foreground service. We load any+ *     persisted [AuthData] off disk.+ *  2. [start] is idempotent: if persisted auth exists, opens the+ *     long-poll and emits Connected. Otherwise sits Idle.+ *  3. [startPair] hits Pairing/RegisterPhoneRelay, stores the initial+ *     tachyon token, opens the long-poll so we can receive the Paired+ *     event, then returns the QR URL for the UI to render.+ *  4. The long-poll dispatches a Paired event → we persist the new+ *     device info + tachyon token, transition to Connected, and trigger+ *     the conversation backfill.+ *  5. [stop] cancels everything and clears the persisted auth.+ *+ * For v1 we LIST_CONVERSATIONS on connect (for backfill / inbox+ * population). [sendMessage] is wired through but stubbed — building+ * the full `SendMessageRequest` payload structure requires more proto+ * coverage than what's needed for receiving and is deferred.+ */+object GMessagesClient {++    private const val TAG = "GMessagesClient"++    sealed interface State {+        data object Idle : State+        data class Pairing(val qrUrl: String) : State+        data object Connected : State+        data class Disconnected(val reason: String) : State+    }++    private val _state = MutableStateFlow<State>(State.Idle)+    val state: StateFlow<State> = _state.asStateFlow()++    private val _events = MutableSharedFlow<GMEvent>(extraBufferCapacity = 256)+    val events: SharedFlow<GMEvent> = _events.asSharedFlow()++    val source: MessageSource = MessageSource.MESSAGES_WEB++    private val initialized = AtomicBoolean(false)+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private lateinit var appContext: Context+    private val rpc = RpcClient()+    @Volatile private var auth: AuthData = AuthData.generateInitial()+    private val sessionHandler = SessionHandler(rpc) { auth }+    private val longPoll = LongPoll(+        rpc = rpc,+        authProvider = { auth },+        sessionHandler = sessionHandler,+        onEvent = ::handleLongPollEvent,+    )+    private var backfillJob: Job? = null++    @Volatile private var conversationsFetchedOnce = false++    fun init(context: Context) {+        if (!initialized.compareAndSet(false, true)) return+        appContext = context.applicationContext+        Log.i(TAG, "init")+        runBlocking {+            AuthData.load(appContext)?.let { auth = it }+        }+        if (auth.isPaired()) {+            Log.i(TAG, "found persisted pair, resuming long-poll")+            longPoll.start(scope)+            _state.value = State.Connected+            kickoffBackfill()+        }+    }++    fun start() {+        if (!initialized.get()) return+        if (auth.isPaired() && _state.value !is State.Connected) {+            longPoll.start(scope)+            _state.value = State.Connected+            kickoffBackfill()+        }+    }++    fun stop() {+        Log.i(TAG, "stop — clearing pair")+        backfillJob?.cancel()+        longPoll.stop()+        sessionHandler.cancelAll()+        auth = AuthData.generateInitial()+        scope.launch { auth.save(appContext) }+        _state.value = State.Idle+    }++    suspend fun startPair(): String {+        // Fresh keys for a fresh pair.+        auth = AuthData.generateInitial()+        val result = PairFlow.registerAndBuildQrUrl(rpc, auth)+        auth = auth.copy(+            tachyonAuthTokenB64 = android.util.Base64.encodeToString(result.tachyonToken, android.util.Base64.NO_WRAP),+            tachyonTtlUs = result.tachyonTtlUs,+            tachyonExpiryMs = System.currentTimeMillis() + (result.tachyonTtlUs / 1000),+        )+        // Open the long-poll now so we receive the Paired event when the+        // user finishes scanning.+        longPoll.start(scope)+        _state.value = State.Pairing(result.qrUrl)+        return result.qrUrl+    }++    @Suppress("UNUSED_PARAMETER")+    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+    }++    /**+     * Load the recent messages for [conversationId] via LIST_MESSAGES.+     * The response flows back through the long-poll into+     * [handleDataMessage] which calls [emitMessage] for each row.+     *+     * Idempotent on the wire — Room upsert deduplicates by message id.+     * Strip the source prefix because the relay only knows Google's+     * thread id.+     */+    fun fetchMessages(conversationId: String, count: Int = 100) {+        if (_state.value !is State.Connected) return+        scope.launch {+            val webId = conversationId.substringAfter(':', conversationId)+            Log.i(TAG, "fetchMessages convId=$webId count=$count")+            val req = ListMessagesRequest.newBuilder()+                .setConversationID(webId)+                .setCount(count.toLong())+                .build()+            val resp = sessionHandler.sendAndWait(ActionType.LIST_MESSAGES, req)+            if (resp == null) Log.w(TAG, "fetchMessages: no response")+        }+    }++    fun forceResync() {+        if (_state.value !is State.Connected) return+        kickoffBackfill()+    }++    // ----------------------------------------------------------------+    // Long-poll event handling+    // ----------------------------------------------------------------++    private suspend fun handleLongPollEvent(evt: LongPollEvent) {+        when (evt) {+            is LongPollEvent.Paired -> {+                // Hand off to our own scope: handlePaired calls longPoll.stop()+                // which would otherwise cancel the very coroutine we're in+                // (the long-poll's reader) mid-execution.+                scope.launch { handlePaired(evt) }+            }+            LongPollEvent.Revoked -> {+                Log.w(TAG, "pair revoked by phone")+                _state.value = State.Disconnected("Pair revoked")+            }+            is LongPollEvent.Data -> handleDataMessage(evt.msg)+        }+    }++    private suspend fun handlePaired(p: LongPollEvent.Paired) {+        Log.i(TAG, "received Paired event — switching to Connected (ttlUs=${p.tachyonTtlUs})")+        auth = auth.copy(+            mobileDeviceB64 = p.mobileDeviceB64,+            browserDeviceB64 = p.browserDeviceB64,+            tachyonAuthTokenB64 = p.tachyonTokenB64,+            tachyonTtlUs = p.tachyonTtlUs,+            tachyonExpiryMs = System.currentTimeMillis() + (p.tachyonTtlUs / 1000),+        )+        auth.save(appContext)+        _state.value = State.Connected++        // CRITICAL: the long-poll that received this Paired event is+        // still authenticated with the INITIAL (pre-pair) tachyon token.+        // The relay routes responses keyed by the long-poll's auth+        // token; subsequent SendMessage calls use the new PERMANENT+        // token after pair, so their responses get routed to a+        // long-poll that doesn't exist. We must close + reopen the+        // long-poll to start listening with the permanent token.+        //+        // Sleep 2 s first to let the phone persist the pair data — if+        // we reconnect too quickly the phone may not recognize the+        // session and silently unpair us (same trick libgm uses in+        // `pair.go` completePairing).+        Log.i(TAG, "sleeping 2s before reconnecting long-poll with permanent token")+        kotlinx.coroutines.delay(2_000)+        longPoll.stop()+        longPoll.start(scope)++        // Give the new long-poll a moment to actually open before the+        // wake-up + backfill RPCs depend on it for their responses.+        kotlinx.coroutines.delay(1_000)+        sessionHandler.setActiveSession(auth.sessionId)+        kotlinx.coroutines.delay(1_000)+        kickoffBackfill()+    }++    private suspend fun handleDataMessage(msg: IncomingRpc) {+        val data = msg.decryptedData ?: return+        when (msg.action) {+            ActionType.LIST_CONVERSATIONS -> {+                val resp = runCatching { ListConversationsResponse.parseFrom(data) }.getOrNull() ?: return+                Log.i(TAG, "backfill: ${resp.conversationsCount} conversations")+                for (i in 0 until resp.conversationsCount) emitConversation(resp.getConversations(i))+            }+            ActionType.LIST_MESSAGES -> {+                val resp = runCatching { ListMessagesResponse.parseFrom(data) }.getOrNull() ?: return+                Log.i(TAG, "thread fill: ${resp.messagesCount} messages")+                // Build all rows up-front then bulk-write in one Room+                // transaction. Per-message events would trigger one Flow+                // emission each — noticeably slow when opening a thread+                // with hundreds of historical messages.+                val rows = (0 until resp.messagesCount).map { idx ->+                    buildMessageRow(resp.getMessages(idx))+                }+                com.vayunmathur.messages.util.MessagesSessionManager.bulkUpsertMessages(rows)+            }+            else -> Log.d(TAG, "unhandled data action ${msg.action}")+        }+    }++    private suspend fun emitConversation(c: conversations.Conversations.Conversation) {+        // Collect the non-self participants — used for both phone-lookup+        // (1:1 chats) and group-display labeling.+        val otherParticipants = (0 until c.participantsCount)+            .map { c.getParticipants(it) }+            .filter { !it.isMe }++        val isGroup = c.isGroupChat || otherParticipants.size > 1+        val peerPhone = otherParticipants.firstOrNull { it.id.number.isNotBlank() }?.id?.number++        // Always prefer the device's contact database for naming + photos+        // (1:1 only). For groups we synthesize a "Alice, Bob & 2 others"+        // style label below.+        val contact = if (!isGroup) {+            peerPhone?.let { ContactResolver.lookup(appContext, it) }+        } else null++        val displayName = when {+            isGroup -> groupLabel(c, otherParticipants)+            else -> contact?.displayName ?: peerPhone ?: c.name.takeIf { it.isNotBlank() }+        }++        val type = when (c.type) {+            conversations.Conversations.ConversationType.SMS -> "SMS"+            conversations.Conversations.ConversationType.RCS -> "RCS"+            else -> null+        }++        _events.emit(+            GMEvent.ConversationUpdate(+                source = source,+                conversationId = c.conversationID,+                peerName = displayName,+                peerPhone = if (isGroup) null else peerPhone,+                avatarUrl = contact?.photoUri,+                lastPreview = if (c.hasLatestMessage()) c.latestMessage.displayContent.takeIf { it.isNotBlank() } else null,+                lastTimestamp = c.lastMessageTimestamp,+                unreadCount = if (c.unread) 1 else 0,+                isGroup = isGroup,+                participantCount = otherParticipants.size,+                conversationType = type,+            )+        )+    }++    /** Build a "Alice, Bob & 2 others" label for a group. Uses the+     *  device's contact name for each participant when available, else+     *  the participant's fullName from the relay, else their number. */+    private fun groupLabel(+        c: conversations.Conversations.Conversation,+        others: List<conversations.Conversations.Participant>,+    ): String {+        // Prefer the explicit thread name (RCS groups often have one).+        val explicit = c.name.takeIf { it.isNotBlank() }+        if (explicit != null) return explicit+        val names = others.map { p ->+            val phone = p.id.number.takeIf { it.isNotBlank() }+            val deviceName = phone?.let { ContactResolver.lookup(appContext, it)?.displayName }+            deviceName+                ?: p.firstName.takeIf { it.isNotBlank() }+                ?: p.fullName.takeIf { it.isNotBlank() }+                ?: phone+                ?: "Unknown"+        }+        return when {+            names.isEmpty() -> "Group"+            names.size <= 2 -> names.joinToString(", ")+            else -> names.take(2).joinToString(", ") + " & ${names.size - 2} others"+        }+    }++    /** Pure transformation of one proto Message into a Room row.+     *  Used by the bulk LIST_MESSAGES path. */+    private fun buildMessageRow(m: conversations.Conversations.Message): com.vayunmathur.messages.data.Message {+        val body = (0 until m.messageInfoCount)+            .mapNotNull { idx ->+                val info = m.getMessageInfo(idx)+                if (info.hasMessageContent()) info.messageContent.content else null+            }+            .joinToString("\n")+        val outgoing = m.hasSenderParticipant() && m.senderParticipant.isMe+        val sourcePrefix = source.idPrefix+        return com.vayunmathur.messages.data.Message(+            id = "$sourcePrefix:${m.messageID}",+            conversationId = "$sourcePrefix:${m.conversationID}",+            body = body,+            direction = if (outgoing) com.vayunmathur.messages.data.MessageDirection.OUTGOING+                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,+            senderName = if (m.hasSenderParticipant()) {+                m.senderParticipant.fullName.takeIf { it.isNotBlank() }+                    ?: m.senderParticipant.firstName.takeIf { it.isNotBlank() }+            } else null,+            reactionsJson = extractReactionsJson(m),+        )+    }++    /** 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? {+        if (m.reactionsCount == 0) return null+        val reactions = (0 until m.reactionsCount).mapNotNull { idx ->+            val entry = m.getReactions(idx)+            val emoji = entry.data.unicode.takeIf { it.isNotBlank() } ?: return@mapNotNull null+            com.vayunmathur.messages.data.Reaction(+                emoji = emoji,+                count = entry.participantIDsCount.coerceAtLeast(1),+            )+        }+        if (reactions.isEmpty()) return null+        return kotlinx.serialization.json.Json.encodeToString(+            kotlinx.serialization.builtins.ListSerializer(+                com.vayunmathur.messages.data.Reaction.serializer()+            ),+            reactions,+        )+    }++    private suspend fun emitMessage(m: conversations.Conversations.Message) {+        // Concatenate all text-bearing MessageInfo parts. Most messages+        // have exactly one; RCS / MMS can have multiple parts (e.g. a+        // caption + an attachment we don't render yet).+        val body = (0 until m.messageInfoCount)+            .mapNotNull { idx ->+                val info = m.getMessageInfo(idx)+                if (info.hasMessageContent()) info.messageContent.content else null+            }+            .joinToString("\n")+            .ifBlank { "" }+        // The Message proto has no top-level fromMe boolean, but its+        // senderParticipant carries an `isMe` flag the relay populates+        // for outgoing messages. Falls back to incoming when missing.+        val outgoing = m.hasSenderParticipant() && m.senderParticipant.isMe+        _events.emit(+            GMEvent.MessageUpdate(+                source = source,+                conversationId = m.conversationID,+                messageId = m.messageID,+                body = body,+                outgoing = outgoing,+                timestamp = m.timestamp,+                senderName = if (m.hasSenderParticipant()) {+                    m.senderParticipant.fullName.takeIf { it.isNotBlank() }+                        ?: m.senderParticipant.firstName.takeIf { it.isNotBlank() }+                } else null,+                reactionsJson = extractReactionsJson(m),+            )+        )+        if (!outgoing && body.isNotEmpty()) {+            _events.emit(+                GMEvent.IncomingMessage(+                    source = source,+                    conversationId = m.conversationID,+                    messageId = m.messageID,+                    body = body,+                    peerName = if (m.hasSenderParticipant()) {+                        m.senderParticipant.fullName.takeIf { it.isNotBlank() }+                    } else null,+                    peerPhone = if (m.hasSenderParticipant()) {+                        m.senderParticipant.id.number.takeIf { it.isNotBlank() }+                    } else null,+                    timestamp = m.timestamp,+                )+            )+        }+    }++    private fun kickoffBackfill() {+        backfillJob?.cancel()+        backfillJob = scope.launch {+            // First call uses BUGLE_ANNOTATION as a "give me everything"+            // hint to the relay; subsequent calls use BUGLE_MESSAGE. See+            // libgm `methods.go.ListConversations` for the same trick.+            val msgType = if (!conversationsFetchedOnce) {+                conversationsFetchedOnce = true+                MessageType.BUGLE_ANNOTATION+            } else {+                MessageType.BUGLE_MESSAGE+            }+            Log.i(TAG, "kicking off LIST_CONVERSATIONS (messageType=$msgType)")+            val req = ListConversationsRequest.newBuilder()+                .setCount(50)+                .build()+            val resp = sessionHandler.sendAndWait(+                ActionType.LIST_CONVERSATIONS,+                req,+                messageType = msgType,+            )+            if (resp == null) {+                Log.w(TAG, "backfill: no response (timeout?)")+            } else {+                Log.i(TAG, "backfill response received (decryptedBytes=${resp.decryptedData?.size ?: 0})")+            }+        }+    }+}
messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.ktnew file mode 100644index 0000000000..5ed1a83019--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt@@ -0,0 +1,295 @@+package com.vayunmathur.messages.gmessages++import android.util.Base64+import android.util.Log+import authentication.Authentication.AuthMessage+import authentication.Authentication.PairedData+import client.Client.ReceiveMessagesRequest+import com.google.protobuf.InvalidProtocolBufferException+import events.Events.RPCPairData+import io.ktor.client.statement.bodyAsChannel+import io.ktor.utils.io.readAvailable+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import rpc.Rpc.BugleRoute+import rpc.Rpc.IncomingRPCMessage+import rpc.Rpc.LongPollingPayload+import rpc.Rpc.RPCMessageData++/**+ * Port of `pkg/libgm/longpoll.go` (minus the ditto pinger).+ *+ * Long-poll response body framing:+ *   - Opens with `[[`+ *   - Each message: a pblite-encoded JSON array delimited by `,`+ *   - Closes with `]]`+ *+ * We accumulate bytes into a buffer; once the buffer parses as valid+ * pblite, we dispatch the [LongPollingPayload] and clear the+ * accumulator. Reconnect on any clean close or error with exponential+ * backoff (5 s → 60 s).+ */+class LongPoll(+    private val rpc: RpcClient,+    private val authProvider: () -> AuthData,+    private val sessionHandler: SessionHandler,+    private val onEvent: suspend (LongPollEvent) -> Unit,+) {+    private var job: Job? = null++    fun start(scope: CoroutineScope) {+        if (job?.isActive == true) return+        job = scope.launch { loop() }+    }++    fun stop() {+        job?.cancel()+        job = null+    }++    private suspend fun loop() {+        var backoffMs = 0L+        while (true) {+            if (backoffMs > 0) {+                Log.i(TAG, "reconnecting in ${backoffMs / 1000}s")+                delay(backoffMs)+            }+            val ok = try {+                openAndRead()+            } catch (t: Throwable) {+                Log.w(TAG, "long-poll error: ${t.message}")+                false+            }+            if (!kotlin.coroutines.coroutineContext.isActive) return+            backoffMs = if (ok) 0L else (if (backoffMs == 0L) 5_000L else minOf(60_000L, backoffMs * 2))+        }+    }++    private suspend fun openAndRead(): Boolean {+        val auth = authProvider()+        val token = auth.tachyonToken() ?: run {+            Log.w(TAG, "no tachyon token, can't open long-poll")+            return false+        }++        val payload = ReceiveMessagesRequest.newBuilder()+            .setAuth(+                AuthMessage.newBuilder()+                    .setRequestID(java.util.UUID.randomUUID().toString())+                    .setNetwork(PairFlow.QrNetwork)+                    .setTachyonAuthToken(token.toByteString())+                    .setConfigVersion(PairFlow.ConfigVersion)+            )+            .setUnknown(+                ReceiveMessagesRequest.UnknownEmptyObject2.newBuilder()+                    .setUnknown(ReceiveMessagesRequest.UnknownEmptyObject1.getDefaultInstance())+            )+            .build()++        // Log the actual JSON we send so we can spot encoder bugs.+        val pbliteBody = PbLite.encode(payload)+        Log.i(TAG, "opening long-poll with body: $pbliteBody")+        return rpc.openLongPoll(Endpoints.ReceiveMessagesUrl, payload) { response ->+            if (response.status.value !in 200..299) {+                Log.e(TAG, "long-poll HTTP ${response.status.value}")+                return@openLongPoll false+            }+            Log.i(TAG, "long-poll open (HTTP ${response.status.value})")+            consumeBody(response.bodyAsChannel())+        }+    }++    private suspend fun consumeBody(channel: io.ktor.utils.io.ByteReadChannel): Boolean {+        // Body framing per `pkg/libgm/longpoll.go.readLongPoll`:+        //   - First two bytes: `[[`+        //   - Each message: a pblite-encoded JSON array (also starting+        //     with `[`), separated by `,`+        //   - Stream end: `]]`+        // We walk bytes once, tracking JSON bracket depth with string-+        // escape awareness, and emit one message every time depth returns+        // to 0 at the top level of the outer array.+        val readBuf = ByteArray(64 * 1024)+        val accumulator = ByteArrayBuilder()+        var sawAnyEvent = false+        var depth = 0+        var inString = false+        var escape = false+        var skippedOpening = false+        var openingBracketsSeen = 0+        var totalBytesRead = 0L++        while (!channel.isClosedForRead) {+            val n = channel.readAvailable(readBuf, 0, readBuf.size)+            if (n <= 0) break+            totalBytesRead += n+            if (totalBytesRead <= 512) {+                Log.i(+                    TAG,+                    "first $n bytes (acc=${totalBytesRead}): ${String(readBuf, 0, minOf(n, 200))}",+                )+            }++            for (i in 0 until n) {+                val b = readBuf[i]+                val c = b.toInt().toChar()++                if (!skippedOpening) {+                    if (c == '[') {+                        openingBracketsSeen+++                        if (openingBracketsSeen >= 2) skippedOpening = true+                        continue+                    }+                    if (c.isWhitespace()) continue+                    skippedOpening = true+                }++                if (depth == 0 && accumulator.isEmpty()) {+                    if (c == ',' || c.isWhitespace()) continue+                    if (c == ']') continue  // stream-end marker+                }++                accumulator.append(b)++                when {+                    escape -> escape = false+                    c == '\\' && inString -> escape = true+                    c == '"' -> inString = !inString+                    inString -> Unit+                    c == '[' || c == '{' -> depth+++                    c == ']' || c == '}' -> {+                        depth--+                        if (depth == 0) {+                            val snapshot = accumulator.toByteArray()+                            accumulator.reset()+                            val parsed = try {+                                PbLite.decode<LongPollingPayload>(+                                    String(snapshot, Charsets.UTF_8),+                                    LongPollingPayload.newBuilder(),+                                )+                            } catch (t: Throwable) {+                                Log.w(TAG, "pblite decode failed: ${t.message}; raw=${String(snapshot, Charsets.UTF_8).take(200)}")+                                null+                            }+                            if (parsed != null) {+                                dispatchPayload(parsed)+                                sawAnyEvent = true+                            }+                        }+                    }+                }+            }+        }+        Log.i(TAG, "long-poll closed (totalBytes=$totalBytesRead events=$sawAnyEvent)")+        return sawAnyEvent+    }++    private suspend fun dispatchPayload(payload: LongPollingPayload) {+        when {+            payload.hasData() -> {+                Log.d(TAG, "dispatch: data (bugleRoute=${payload.data.bugleRoute})")+                handleData(payload.data)+            }+            payload.hasHeartbeat() -> Log.d(TAG, "dispatch: heartbeat")+            payload.hasAck() -> Log.d(TAG, "got startup ack count=${payload.ack.count}")+            payload.hasStartRead() -> Log.d(TAG, "got startRead marker")+            else -> Log.d(TAG, "long-poll unknown payload type")+        }+    }++    private suspend fun handleData(data: IncomingRPCMessage) {+        when (data.bugleRoute) {+            BugleRoute.PairEvent -> handlePairEvent(data)+            BugleRoute.DataEvent -> handleDataEvent(data)+            else -> Log.d(TAG, "skipping bugle route ${data.bugleRoute}")+        }+    }++    private suspend fun handlePairEvent(data: IncomingRPCMessage) {+        val pair: RPCPairData = try {+            RPCPairData.parseFrom(data.messageData)+        } catch (e: InvalidProtocolBufferException) {+            Log.e(TAG, "failed to decode RPCPairData", e)+            return+        }+        when {+            pair.hasPaired() -> {+                val p: PairedData = pair.paired+                onEvent(+                    LongPollEvent.Paired(+                        mobileDeviceB64 = Base64.encodeToString(p.mobile.toByteArray(), Base64.NO_WRAP),+                        browserDeviceB64 = Base64.encodeToString(p.browser.toByteArray(), Base64.NO_WRAP),+                        tachyonTokenB64 = Base64.encodeToString(p.tokenData.tachyonAuthToken.toByteArray(), Base64.NO_WRAP),+                        tachyonTtlUs = p.tokenData.ttl,+                    )+                )+            }+            pair.hasRevoked() -> onEvent(LongPollEvent.Revoked)+            else -> Log.d(TAG, "unknown pair event")+        }+    }++    private suspend fun handleDataEvent(data: IncomingRPCMessage) {+        val msg: RPCMessageData = try {+            RPCMessageData.parseFrom(data.messageData)+        } catch (e: InvalidProtocolBufferException) {+            Log.e(TAG, "failed to decode RPCMessageData", e)+            return+        }+        Log.d(+            TAG,+            "data event: action=${msg.action} sessionID=${msg.sessionID} encrypted=${msg.encryptedData.size()}B",+        )+        var decrypted: ByteArray? = null+        if (msg.encryptedData.size() > 0) {+            decrypted = try {+                authProvider().crypto().decrypt(msg.encryptedData.toByteArray())+            } catch (t: Throwable) {+                Log.w(TAG, "failed to decrypt data event payload: ${t.message}")+                null+            }+        }+        val incoming = IncomingRpc(+            responseId = data.responseID,+            requestId = msg.sessionID.takeIf { it.isNotEmpty() },+            action = msg.action,+            decryptedData = decrypted,+        )+        val reqId = msg.sessionID+        if (reqId.isNotEmpty()) sessionHandler.deliverResponse(reqId, incoming)+        onEvent(LongPollEvent.Data(incoming))+    }++    companion object {+        private const val TAG = "GMessages/LongPoll"+    }+}++/** Events the long-poll surfaces to the GMessagesClient. */+sealed interface LongPollEvent {+    data class Paired(+        val mobileDeviceB64: String,+        val browserDeviceB64: String,+        val tachyonTokenB64: String,+        val tachyonTtlUs: Long,+    ) : LongPollEvent++    data object Revoked : LongPollEvent++    data class Data(val msg: IncomingRpc) : LongPollEvent+}++/** Minimal mutable byte buffer to avoid string-conversion overhead. */+private class ByteArrayBuilder(initial: Int = 4096) {+    private var buf = ByteArray(initial)+    private var len = 0+    fun isEmpty(): Boolean = len == 0+    fun append(b: Byte) {+        if (len == buf.size) buf = buf.copyOf(buf.size * 2)+        buf[len++] = b+    }+    fun toByteArray(): ByteArray = buf.copyOf(len)+    fun reset() { len = 0 }+}
messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.ktnew file mode 100644index 0000000000..915986c1c0--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/PairFlow.kt@@ -0,0 +1,132 @@+package com.vayunmathur.messages.gmessages++import android.util.Base64+import android.util.Log+import authentication.Authentication+import authentication.Authentication.AuthenticationContainer+import authentication.Authentication.AuthMessage+import authentication.Authentication.BrowserType+import authentication.Authentication.BrowserDetails+import authentication.Authentication.ConfigVersion+import authentication.Authentication.DeviceType+import authentication.Authentication.ECDSAKeys+import authentication.Authentication.KeyData+import authentication.Authentication.RegisterPhoneRelayResponse+import authentication.Authentication.URLData+import java.util.UUID++/**+ * Implements the QR-code pairing handshake. Direct port of+ * `pkg/libgm/pair.go`.+ *+ * Flow:+ *   1. POST to Pairing/RegisterPhoneRelay with our ECDSA public key+ *      (X.509 SubjectPublicKeyInfo encoding) — the relay returns an+ *      initial tachyon auth token and a one-shot pairing key.+ *   2. Build a URLData{ pairingKey, AESKey, HMACKey } protobuf,+ *      base64-encode it (standard, NOT url-safe), and prefix with+ *      [Endpoints.QrCodeBaseUrl].+ *   3. Render that URL as a QR code (caller's responsibility) and show+ *      it. The user scans it from their phone's Google Messages app+ *      (menu → Device pairing → Pair QR code scanner).+ *   4. The phone POSTs the pair completion to the relay, which pushes+ *      a Paired event back through our long-poll. [LongPoll] handles+ *      that and calls [AuthData.applyPaired].+ */+object PairFlow {++    private const val TAG = "GMessages/Pair"++    /** Network name on the QR-pair path (vs. "GDitto" for the+     *  Google-account-based GAIA path we don't support). */+    const val QrNetwork = "Bugle"++    /** Config version that messages.google.com/web is currently sending.+     *  Kept in sync with libgm `util/config.go.ConfigMessage`. Lazy so+     *  the proto runtime is initialized before we touch the builders. */+    val ConfigVersion: ConfigVersion by lazy {+        authentication.Authentication.ConfigVersion.newBuilder()+            .setYear(2026).setMonth(3).setDay(18).setV1(4).setV2(6)+            .build()+    }++    /** Browser-identification protobuf sent on every auth request. */+    val BrowserDetails: BrowserDetails by lazy {+        authentication.Authentication.BrowserDetails.newBuilder()+            .setUserAgent(Endpoints.UserAgent)+            .setBrowserType(BrowserType.OTHER)+            .setOS("modern-apps-messages")+            .setDeviceType(DeviceType.TABLET)+            .build()+    }++    /**+     * Step 1 + 2: register a phone-relay slot and return both the+     * initial tachyon token (so the long-poll can immediately connect+     * to receive the eventual Paired event) and the QR URL the user+     * should scan.+     */+    suspend fun registerAndBuildQrUrl(+        rpc: RpcClient,+        auth: AuthData,+    ): RegisterResult {+        val pubKey = auth.refreshKey.publicKeyDer()+        val req = AuthenticationContainer.newBuilder()+            .setAuthMessage(+                AuthMessage.newBuilder()+                    .setRequestID(UUID.randomUUID().toString())+                    .setNetwork(QrNetwork)+                    .setConfigVersion(ConfigVersion)+            )+            .setBrowserDetails(BrowserDetails)+            .setKeyData(+                KeyData.newBuilder()+                    .setEcdsaKeys(+                        ECDSAKeys.newBuilder()+                            .setField1(2)+                            .setEncryptedKeys(pubKey.toByteString())+                    )+            )+            .build()++        Log.i(TAG, "RegisterPhoneRelay …")+        val resp = rpc.postProtobuf(+            url = Endpoints.RegisterPhoneRelayUrl,+            body = req,+            responseTemplate = RegisterPhoneRelayResponse.getDefaultInstance(),+        )+        Log.i(TAG, "RegisterPhoneRelay OK; tachyon token ${resp.authKeyData.tachyonAuthToken.size()} bytes")++        val urlData = URLData.newBuilder()+            .setPairingKey(resp.pairingKey)+            .setAESKey(auth.crypto().aesKey.toByteString())+            .setHMACKey(auth.crypto().hmacKey.toByteString())+            .build()+        val qrPayload = Base64.encodeToString(urlData.toByteArray(), Base64.NO_WRAP)+        val qrUrl = Endpoints.QrCodeBaseUrl + qrPayload++        return RegisterResult(+            tachyonToken = resp.authKeyData.tachyonAuthToken.toByteArray(),+            tachyonTtlUs = resp.authKeyData.ttl,+            qrUrl = qrUrl,+        )+    }++    data class RegisterResult(+        val tachyonToken: ByteArray,+        val tachyonTtlUs: Long,+        val qrUrl: String,+    )++    /**+     * Refresh the tachyon token via Pairing/RefreshPhoneRelay using+     * the persisted ECDSA RefreshKey. Returns the new token + TTL.+     * Called periodically by the session manager before the current+     * TTL expires.+     */+    // refreshTachyonToken removed in v1 — the real refresh path uses+    // the separate `Registration.RegisterRefresh` endpoint (not+    // Pairing.RefreshPhoneRelay, which only regenerates a fresh QR for+    // re-pairing). Token TTL is several days; for v1 we surface a+    // re-pair prompt if the user gets logged out.+}
messages/src/main/java/com/vayunmathur/messages/gmessages/PbLite.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/PbLite.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/PbLite.ktnew file mode 100644index 0000000000..7f404c27ee--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/PbLite.kt@@ -0,0 +1,189 @@+package com.vayunmathur.messages.gmessages++import android.util.Base64+import com.google.protobuf.Descriptors.FieldDescriptor+import com.google.protobuf.MessageOrBuilder+import com.google.protobuf.Message+import org.json.JSONArray+import org.json.JSONObject+import org.json.JSONTokener+import com.google.protobuf.ByteString++/**+ * Encoder/decoder for Google's "PB-Lite" wire format. Direct port of the+ * reflection-driven implementation in+ * https://github.com/mautrix/go-util/tree/main/pblite.+ *+ * PB-Lite encodes a protobuf message as a positional JSON array where+ * index `i` holds field number `i + 1`. Holes are JSON null. Nested+ * messages become nested arrays. Repeated fields become flat arrays of+ * encoded values. Bytes-typed fields become base64 strings.+ *+ * Messages-for-Web uses this format for the SendMessage RPC body+ * (`Content-Type: application/json+protobuf`). Inbound responses use+ * regular binary protobuf — see [decodeProtobuf] in [RpcClient].+ *+ * Implementation reads/writes via the standard protobuf descriptor+ * reflection API (requires the full `protobuf-java` runtime, not the+ * `-lite` variant, since lite drops reflection).+ */+object PbLite {++    fun encode(message: MessageOrBuilder): String {+        val arr = serializeMessage(message)+        return arr.toString()+    }++    @Suppress("UNCHECKED_CAST")+    fun <T : Message> decode(json: String, builderTemplate: Message.Builder): T {+        val parsed = JSONTokener(json).nextValue()+        require(parsed is JSONArray) {+            "expected top-level JSON array for pblite, got ${parsed?.javaClass?.simpleName}"+        }+        deserializeMessage(parsed, builderTemplate)+        return builderTemplate.build() as T+    }++    private fun serializeMessage(message: MessageOrBuilder): JSONArray {+        val desc = message.descriptorForType+        val fields = desc.fields+        // Find the highest field number to size the array.+        val maxFieldNumber = fields.maxOfOrNull { it.number } ?: 0+        val arr = JSONArray()+        // JSONArray doesn't have a fixed-size constructor; pad with nulls.+        repeat(maxFieldNumber) { arr.put(JSONObject.NULL) }+        for (field in fields) {+            if (!hasField(message, field)) continue+            val idx = field.number - 1+            val value = message.getField(field)+            arr.put(idx, encodeFieldValue(field, value))+        }+        return arr+    }++    /** Encode a single field value (may be a List for repeated fields). */+    private fun encodeFieldValue(field: FieldDescriptor, value: Any): Any {+        if (field.isRepeated) {+            val list = value as List<*>+            val arr = JSONArray()+            for (v in list) {+                arr.put(encodeScalar(field, v!!))+            }+            return arr+        }+        return encodeScalar(field, value)+    }++    private fun encodeScalar(field: FieldDescriptor, value: Any): Any = when (field.javaType) {+        FieldDescriptor.JavaType.INT -> (value as Number).toLong()+        FieldDescriptor.JavaType.LONG -> {+            // Match how Google's web client serializes int64 — values+            // outside the JS-safe range (|v| > 2^53) become quoted strings.+            // Server is more lenient when receiving but we mirror what+            // the real web client sends for forward-compatibility.+            val v = (value as Number).toLong()+            if (v > 9_007_199_254_740_992L || v < -9_007_199_254_740_992L) v.toString() else v+        }+        FieldDescriptor.JavaType.FLOAT, FieldDescriptor.JavaType.DOUBLE -> (value as Number).toDouble()+        FieldDescriptor.JavaType.BOOLEAN -> value as Boolean+        FieldDescriptor.JavaType.STRING -> value as String+        FieldDescriptor.JavaType.BYTE_STRING -> {+            val bs = value as ByteString+            Base64.encodeToString(bs.toByteArray(), Base64.NO_WRAP)+        }+        FieldDescriptor.JavaType.ENUM -> {+            val ev = value as com.google.protobuf.Descriptors.EnumValueDescriptor+            ev.number.toLong()+        }+        FieldDescriptor.JavaType.MESSAGE -> serializeMessage(value as MessageOrBuilder)+        else -> error("unsupported pblite java type ${field.javaType}")+    }++    /** Honour the protobuf3 "presence" rules: scalar fields are present+     *  iff they have a non-default value (the descriptor API exposes+     *  hasField only for messages + optional fields). */+    private fun hasField(message: MessageOrBuilder, field: FieldDescriptor): Boolean {+        if (field.isRepeated) return (message.getField(field) as List<*>).isNotEmpty()+        if (field.hasPresence()) return message.hasField(field)+        val v = message.getField(field)+        return when (field.javaType) {+            FieldDescriptor.JavaType.INT, FieldDescriptor.JavaType.LONG -> (v as Number).toLong() != 0L+            FieldDescriptor.JavaType.FLOAT, FieldDescriptor.JavaType.DOUBLE -> (v as Number).toDouble() != 0.0+            FieldDescriptor.JavaType.BOOLEAN -> v as Boolean+            FieldDescriptor.JavaType.STRING -> (v as String).isNotEmpty()+            FieldDescriptor.JavaType.BYTE_STRING -> !(v as ByteString).isEmpty+            FieldDescriptor.JavaType.ENUM -> (v as com.google.protobuf.Descriptors.EnumValueDescriptor).number != 0+            FieldDescriptor.JavaType.MESSAGE -> message.hasField(field)+            else -> false+        }+    }++    private fun deserializeMessage(arr: JSONArray, builder: Message.Builder) {+        val desc = builder.descriptorForType+        for (field in desc.fields) {+            val idx = field.number - 1+            if (idx >= arr.length()) continue+            if (arr.isNull(idx)) continue+            val raw = arr.get(idx)+            decodeFieldValue(field, raw, builder)+        }+    }++    private fun decodeFieldValue(field: FieldDescriptor, raw: Any, builder: Message.Builder) {+        if (field.isRepeated) {+            val arr = raw as? JSONArray ?: error("expected array for repeated ${field.fullName}")+            for (i in 0 until arr.length()) {+                if (arr.isNull(i)) continue+                builder.addRepeatedField(field, decodeScalar(field, arr.get(i), builder))+            }+            return+        }+        builder.setField(field, decodeScalar(field, raw, builder))+    }++    private fun decodeScalar(field: FieldDescriptor, raw: Any, parent: Message.Builder): Any = when (field.javaType) {+        FieldDescriptor.JavaType.INT -> coerceLong(raw).toInt()+        FieldDescriptor.JavaType.LONG -> coerceLong(raw)+        FieldDescriptor.JavaType.FLOAT -> coerceDouble(raw).toFloat()+        FieldDescriptor.JavaType.DOUBLE -> coerceDouble(raw)+        FieldDescriptor.JavaType.BOOLEAN -> when (raw) {+            is Boolean -> raw+            is Number -> raw.toInt() != 0+            is String -> raw.toBoolean()+            else -> error("can't coerce ${raw::class.simpleName} to Boolean")+        }+        FieldDescriptor.JavaType.STRING -> raw.toString()+        FieldDescriptor.JavaType.BYTE_STRING -> {+            val s = raw as String+            ByteString.copyFrom(Base64.decode(s, Base64.NO_WRAP))+        }+        FieldDescriptor.JavaType.ENUM -> {+            val n = coerceLong(raw).toInt()+            field.enumType.findValueByNumber(n) ?: field.enumType.values.first()+        }+        FieldDescriptor.JavaType.MESSAGE -> {+            val arr = raw as? JSONArray ?: error("expected array for message ${field.fullName}")+            val sub = parent.newBuilderForField(field)+            deserializeMessage(arr, sub)+            sub.build()+        }+        else -> error("unsupported pblite java type ${field.javaType}")+    }++    /**+     * PB-Lite encodes large int64s as JSON strings (to dodge JavaScript's+     * 53-bit safe-integer limit). Also tolerates numbers wrapped as+     * various Number subtypes by JSON parsers.+     */+    private fun coerceLong(raw: Any): Long = when (raw) {+        is Number -> raw.toLong()+        is String -> raw.toLong()+        else -> error("can't coerce ${raw::class.simpleName} to Long")+    }++    private fun coerceDouble(raw: Any): Double = when (raw) {+        is Number -> raw.toDouble()+        is String -> raw.toDouble()+        else -> error("can't coerce ${raw::class.simpleName} to Double")+    }+}
messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.ktnew file mode 100644index 0000000000..b6fa56f84f--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/RpcClient.kt@@ -0,0 +1,191 @@+package com.vayunmathur.messages.gmessages++import android.util.Log+import com.google.protobuf.Message+import com.google.protobuf.MessageOrBuilder+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.preparePost+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.client.statement.bodyAsChannel+import io.ktor.http.ContentType+import io.ktor.http.HttpMethod+import io.ktor.http.contentType+import io.ktor.utils.io.ByteReadChannel++/**+ * HTTP transport for the Google-Messages-for-Web RPC protocol.+ *+ * Mirrors `pkg/libgm/http.go`:+ *   - All requests are POSTs to the RPC URLs (`$rpc/.../<Method>`).+ *   - Bodies are either protobuf binary (`application/x-protobuf`) or+ *     pblite JSON-array (`application/json+protobuf`).+ *   - Every request carries the relay headers from+ *     [Endpoints] + `util/func.go.BuildRelayHeaders` (Sec-CH-UA,+ *     User-Agent, X-Goog-API-Key, etc).+ *+ * Two underlying Ktor clients exist because long-poll requests need a+ * much longer read timeout than normal RPC.+ */+class RpcClient {++    private val normal: HttpClient = HttpClient(CIO) {+        engine {+            requestTimeout = 30_000  // 30 s+        }+        install(HttpTimeout) {+            requestTimeoutMillis = 30_000+            connectTimeoutMillis = 15_000+            socketTimeoutMillis = 30_000+        }+    }++    private val longPoll: HttpClient = HttpClient(CIO) {+        engine {+            // No request-level timeout — long polls can sit open for+            // several minutes between heartbeats.+            requestTimeout = 0+        }+        install(HttpTimeout) {+            // Total request budget: 6 minutes. Beyond that we cycle.+            requestTimeoutMillis = 6 * 60 * 1000+            connectTimeoutMillis = 15_000+            // Socket-level idle timeout above 1 minute so heartbeats+            // (every ~minute) keep the stream alive.+            socketTimeoutMillis = 90_000+        }+    }++    fun close() {+        runCatching { normal.close() }+        runCatching { longPoll.close() }+    }++    /**+     * POST [body] as binary protobuf and decode the response as the+     * template's message type. Uses the normal client.+     */+    suspend fun <T : Message> postProtobuf(+        url: String,+        body: Message,+        responseTemplate: T,+    ): T {+        val resp = post(url, body.toByteArray(), ContentTypes.Protobuf, longPoll = false)+        return decodeBody(resp, responseTemplate)+    }++    /**+     * POST [body] as a pblite JSON array. Used for SendMessage and Ack.+     * Most responses we care about are empty-ish OutgoingRPCResponse+     * acks (any failure is conveyed via HTTP status).+     */+    suspend fun postPbLite(+        url: String,+        body: Message,+    ): HttpResponse {+        val json = PbLite.encode(body)+        return post(url, json.toByteArray(Charsets.UTF_8), ContentTypes.PbLite, longPoll = false)+    }++    /**+     * Open a long-poll: POSTs the request body as pblite and invokes+     * [onResponse] with the live [HttpResponse]. The body MUST be+     * consumed via the streaming channel API ([bodyAsChannel]); calling+     * [HttpResponse.bodyAsBytes] would buffer-then-block.+     *+     * The connection is held open for the duration of the callback,+     * then closed cleanly. Returns whatever [onResponse] returned.+     *+     * Implemented via `preparePost().execute { ... }` rather than+     * `request()` because the latter eagerly reads the entire response+     * body before returning — fine for short RPCs, fatal for long-poll+     * where the body is an unbounded stream of pushed events.+     */+    suspend fun <T> openLongPoll(+        url: String,+        body: Message,+        onResponse: suspend (HttpResponse) -> T,+    ): T {+        val json = PbLite.encode(body)+        val bytes = json.toByteArray(Charsets.UTF_8)+        Log.d(TAG, "POST $url (${bytes.size} bytes, ${ContentTypes.PbLite}) [long-poll]")+        return longPoll.preparePost(url) {+            method = HttpMethod.Post+            contentType(ContentType.parse(ContentTypes.PbLite))+            applyRelayHeaders(ContentTypes.PbLite, accept = "*/*")+            setBody(bytes)+        }.execute { response ->+            onResponse(response)+        }+    }++    private suspend fun post(+        url: String,+        body: ByteArray,+        contentType: String,+        longPoll: Boolean,+    ): HttpResponse {+        val client = if (longPoll) this.longPoll else normal+        Log.d(TAG, "POST $url (${body.size} bytes, $contentType)")+        return client.request(url) {+            method = HttpMethod.Post+            contentType(ContentType.parse(contentType))+            applyRelayHeaders(contentType, accept = "*/*")+            setBody(body)+        }+    }++    private fun io.ktor.client.request.HttpRequestBuilder.applyRelayHeaders(+        contentType: String,+        accept: String,+    ) {+        // Port of util.BuildRelayHeaders. Each `Sec-Fetch-*` header is+        // what real Chrome sends for the cross-site fetch; Google's+        // anti-abuse layer reads these to distinguish browser traffic+        // from random clients.+        headers {+            append("sec-ch-ua", Endpoints.SecUA)+            append("x-user-agent", Endpoints.XUserAgent)+            append("x-goog-api-key", Endpoints.GoogleApiKey)+            append("sec-ch-ua-mobile", Endpoints.SecUAMobile)+            append("user-agent", Endpoints.UserAgent)+            append("sec-ch-ua-platform", "\"${Endpoints.UAPlatform}\"")+            append("accept", 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")+        }+    }++    private suspend fun <T : Message> decodeBody(resp: HttpResponse, template: T): T {+        require(resp.status.value in 200..299) {+            "HTTP ${resp.status.value} ${resp.status.description}"+        }+        val ct = resp.headers["Content-Type"].orEmpty().lowercase()+        val bytes = resp.bodyAsBytes()+        @Suppress("UNCHECKED_CAST")+        return when {+            ct.contains("x-protobuf") -> template.parserForType.parseFrom(bytes) as T+            ct.contains("json") || ct.startsWith("text/plain") -> {+                val builder = template.newBuilderForType()+                PbLite.decode<T>(String(bytes, Charsets.UTF_8), builder)+            }+            else -> error("unknown response content-type: $ct")+        }+    }++    companion object {+        private const val TAG = "GMessages/RpcClient"+    }+}++/** Convenience: open a long-poll's body channel for streaming reads. */+suspend fun HttpResponse.bodyChannel(): ByteReadChannel = bodyAsChannel()
messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.ktnew file mode 100644index 0000000000..f50e636ab0--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt@@ -0,0 +1,224 @@+package com.vayunmathur.messages.gmessages++import android.util.Log+import com.google.protobuf.Message+import com.vayunmathur.messages.gmessages.PairFlow.ConfigVersion+import authentication.Authentication.AuthMessage+import rpc.Rpc.ActionType+import rpc.Rpc.BugleRoute+import rpc.Rpc.MessageType+import rpc.Rpc.OutgoingRPCData+import rpc.Rpc.OutgoingRPCMessage+import java.util.UUID+import java.util.concurrent.ConcurrentHashMap+import io.ktor.client.statement.bodyAsBytes+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.withTimeoutOrNull++/**+ * Port of `pkg/libgm/session_handler.go`.+ *+ * Responsibilities:+ *  - Build outgoing RPC envelopes (sets the Auth fields, encrypts the+ *    payload with [AuthData.crypto], assembles the OutgoingRPCMessage).+ *  - Send via [RpcClient.postPbLite].+ *  - Match relay responses (delivered out-of-band via the long-poll)+ *    back to in-flight requests by request-ID.+ */+class SessionHandler(+    private val rpc: RpcClient,+    private val authProvider: () -> AuthData,+) {+    private val waiters = ConcurrentHashMap<String, CompletableDeferred<IncomingRpc>>()++    /**+     * Send an RPC and wait up to [timeoutMs] ms for the matching+     * response. Returns null on timeout.+     */+    suspend fun sendAndWait(+        action: ActionType,+        payload: Message?,+        timeoutMs: Long = 30_000,+        messageType: MessageType = MessageType.BUGLE_MESSAGE,+    ): IncomingRpc? {+        val (requestId, envelope) = buildEnvelope(action, payload, messageType)+        val deferred = CompletableDeferred<IncomingRpc>()+        waiters[requestId] = deferred+        Log.i(TAG, "sendAndWait $action requestID=$requestId")+        try {+            // Dump the actual pblite payload so we can compare against+            // what libgm's working implementation sends.+            val pbliteBody = PbLite.encode(envelope)+            Log.i(TAG, "sendAndWait envelope: $pbliteBody")+            val resp = rpc.postPbLite(Endpoints.SendMessageUrl, envelope)+            // Dump the response body so we can see if the relay is+            // returning an error in the body (vs. just 200-with-no-result).+            val respBytes = try { resp.bodyAsBytes() } catch (_: Throwable) { ByteArray(0) }+            Log.i(TAG, "SendMessage HTTP ${resp.status.value}, response body: ${String(respBytes, Charsets.UTF_8).take(500)}")+            if (resp.status.value !in 200..299) {+                Log.w(TAG, "sendAndWait $action: HTTP ${resp.status.value}")+                waiters.remove(requestId)+                return null+            }+            Log.d(TAG, "sendAndWait $action: HTTP 200, waiting for relay response…")+            return withTimeoutOrNull(timeoutMs) { deferred.await() }.also {+                waiters.remove(requestId)+            }+        } catch (t: Throwable) {+            Log.e(TAG, "sendAndWait $action failed", t)+            waiters.remove(requestId)+            return null+        }+    }++    /** Fire-and-forget: don't register a waiter. Used for things like+     *  ack messages where we don't care about the response. */+    suspend fun sendNoWait(action: ActionType, payload: Message?): Boolean {+        val (_, envelope) = buildEnvelope(action, payload, MessageType.BUGLE_MESSAGE)+        return try {+            val resp = rpc.postPbLite(Endpoints.SendMessageUrl, envelope)+            resp.status.value in 200..299+        } catch (t: Throwable) {+            Log.e(TAG, "sendNoWait $action failed", t)+            false+        }+    }++    /**+     * The "wake up" call libgm makes after each pair / reconnect.+     * Sends GET_UPDATES with requestID == the local sessionID and TTL = 0.+     * Without this, a freshly-paired relay won't forward subsequent data+     * events back to us, so LIST_CONVERSATIONS and friends hang forever.+     */+    suspend fun setActiveSession(sessionId: String): Boolean {+        Log.i(TAG, "setActiveSession (GET_UPDATES, requestID=sessionID=$sessionId)")+        val envelope = buildEnvelopeWithFixedRequestId(+            action = ActionType.GET_UPDATES,+            payload = null,+            messageType = MessageType.BUGLE_MESSAGE,+            requestId = sessionId,+            omitTtl = true,+        )+        return try {+            val resp = rpc.postPbLite(Endpoints.SendMessageUrl, envelope)+            val body = try { resp.bodyAsBytes() } catch (_: Throwable) { ByteArray(0) }+            Log.i(TAG, "setActiveSession HTTP ${resp.status.value}, body: ${String(body, Charsets.UTF_8).take(200)}")+            resp.status.value in 200..299+        } catch (t: Throwable) {+            Log.e(TAG, "setActiveSession failed", t)+            false+        }+    }++    /** Called by the long-poll dispatcher when a response arrives. */+    fun deliverResponse(requestId: String, msg: IncomingRpc) {+        val waiter = waiters.remove(requestId)+        if (waiter == null) {+            Log.d(TAG, "no waiter for requestID=$requestId (action=${msg.action})")+            return+        }+        Log.i(TAG, "delivering response for requestID=$requestId action=${msg.action}")+        waiter.complete(msg)+    }++    /** Drop everything (called on stop / reset). */+    fun cancelAll() {+        waiters.values.forEach { it.cancel() }+        waiters.clear()+    }++    private fun buildEnvelope(+        action: ActionType,+        payload: Message?,+        messageType: MessageType,+    ): Pair<String, OutgoingRPCMessage> {+        val requestId = UUID.randomUUID().toString()+        return requestId to buildEnvelopeWithFixedRequestId(+            action = action,+            payload = payload,+            messageType = messageType,+            requestId = requestId,+            omitTtl = false,+        )+    }++    /**+     * Build an envelope with a caller-chosen [requestId]. Used by+     * [setActiveSession] so the requestID can be the sessionID — a+     * libgm-style convention that the relay treats as a wake-up.+     */+    private fun buildEnvelopeWithFixedRequestId(+        action: ActionType,+        payload: Message?,+        messageType: MessageType,+        requestId: String,+        omitTtl: Boolean,+    ): OutgoingRPCMessage {+        val auth = authProvider()+        val sessionId = auth.sessionId++        val serializedPayload = payload?.toByteArray() ?: ByteArray(0)+        val encryptedPayload = if (serializedPayload.isNotEmpty()) {+            auth.crypto().encrypt(serializedPayload)+        } else ByteArray(0)++        val rpcData = OutgoingRPCData.newBuilder()+            .setRequestID(requestId)+            .setAction(action)+            .setEncryptedProtoData(encryptedPayload.toByteString())+            .setSessionID(sessionId)+            .build()++        val builder = OutgoingRPCMessage.newBuilder()+            .setData(+                OutgoingRPCMessage.Data.newBuilder()+                    .setRequestID(requestId)+                    .setBugleRoute(BugleRoute.DataEvent)+                    .setMessageData(rpcData.toByteString())+                    .setMessageTypeData(+                        OutgoingRPCMessage.Data.Type.newBuilder()+                            .setEmptyArr(util.Util.EmptyArr.getDefaultInstance())+                            .setMessageType(messageType)+                    )+            )+            .setAuth(+                OutgoingRPCMessage.Auth.newBuilder()+                    .setRequestID(requestId)+                    .setTachyonAuthToken(auth.tachyonToken()!!.toByteString())+                    .setConfigVersion(PairFlow.ConfigVersion)+            )++        if (!omitTtl) builder.setTTL(auth.tachyonTtlUs)++        auth.mobile()?.let { builder.setMobile(it) }+        return builder.build()+    }++    companion object {+        private const val TAG = "GMessages/Session"+    }+}++/**+ * Decoded incoming RPC message — either a paired event, a response to+ * one of our outbound RPCs, or a server-pushed update.+ *+ * Mirrors libgm's `IncomingRPCMessage` struct (event_handler.go) but+ * keeps just the v1-essential fields.+ */+data class IncomingRpc(+    val responseId: String,+    val requestId: String?,+    val action: ActionType?,+    /** Decrypted payload bytes, if any. */+    val decryptedData: ByteArray?,+    /** Raw decoded pair event (BugleRoute=PairEvent), if applicable. */+    val pairEvent: PairEventKind = PairEventKind.None,+    /** Paired data when [pairEvent] is [PairEventKind.Paired]. */+    val pairedDeviceMobileB64: String? = null,+    val pairedDeviceBrowserB64: String? = null,+    val pairedTachyonTokenB64: String? = null,+    val pairedTachyonTtlUs: Long = 0L,+)++enum class PairEventKind { None, Paired, Revoked }
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.ktnew file mode 100644index 0000000000..e0b45d2fa5--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/ui/ConversationScreen.kt@@ -0,0 +1,491 @@+package com.vayunmathur.messages.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+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.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.widthIn+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.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Scaffold+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.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+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+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.IconNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.messages.R+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.MessageState+import com.vayunmathur.messages.data.MessagesDatabase+import com.vayunmathur.messages.data.Reaction+import com.vayunmathur.messages.util.MessagesViewModel+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.json.Json+import java.text.DateFormat+import java.text.SimpleDateFormat+import java.util.Calendar+import java.util.Date+import java.util.Locale++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ConversationScreen(+    backStack: NavBackStack<Route>,+    vm: MessagesViewModel,+    db: MessagesDatabase,+    conversationId: String,+) {+    val conversation by db.conversationDao().observe(conversationId).collectAsState(initial = null)+    val messages by db.messageDao().observeForConversation(conversationId)+        .collectAsState(initial = emptyList())++    LaunchedEffect(conversationId) {+        vm.markRead(conversationId)+        vm.fetchMessages(conversationId)+    }++    var draft by remember { mutableStateOf("") }+    var sending by remember { mutableStateOf(false) }++    val listState = rememberLazyListState()++    Scaffold(+        topBar = {+            TopAppBar(+                title = {+                    Row(verticalAlignment = Alignment.CenterVertically) {+                        ConvAvatar(conversation)+                        Spacer(Modifier.size(12.dp))+                        Column {+                            Text(+                                conversation?.peerName ?: "Conversation",+                                fontWeight = FontWeight.SemiBold,+                            )+                            conversation?.let {+                                Text(+                                    it.conversationType ?: if (it.isGroup) "Group" else "",+                                    fontSize = 11.sp,+                                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                                )+                            }+                        }+                    }+                },+                navigationIcon = { IconNavigation(backStack) },+                colors = TopAppBarDefaults.topAppBarColors(+                    containerColor = MaterialTheme.colorScheme.surface,+                ),+            )+        },+        bottomBar = {+            ComposeRow(+                draft = draft,+                onDraftChange = { draft = it },+                sending = sending,+                onSend = {+                    val toSend = draft.trim()+                    if (toSend.isEmpty()) return@ComposeRow+                    sending = true+                    vm.send(conversationId, toSend) { _ -> sending = false }+                    draft = ""+                },+            )+        },+    ) { padding ->+        if (messages.isEmpty()) {+            Box(+                Modifier.padding(padding).fillMaxSize(),+                contentAlignment = Alignment.Center,+            ) {+                Column(horizontalAlignment = Alignment.CenterHorizontally) {+                    CircularProgressIndicator()+                    Spacer(Modifier.size(12.dp))+                    Text(+                        "Loading messages…",+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }+            }+        } else {+            // Walk the message list once, emitting (day-divider, message)+            // pairs so the UI can render them inline. Cheaper than a+            // groupBy on every recomposition.+            //+            // The LazyColumn below uses reverseLayout = true so item 0+            // sits at the visual bottom — the standard messenger pattern+            // (sparse threads pack to the bottom, new messages slot in+            // without a jumpy scroll-to-end). To get that visual order+            // we feed it the chronological list REVERSED: newest first.+            val items = remember(messages) { buildItems(messages).asReversed() }+            val isGroup = conversation?.isGroup == true+            LazyColumn(+                state = listState,+                reverseLayout = true,+                modifier = Modifier+                    .padding(padding)+                    .fillMaxSize(),+                contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),+                verticalArrangement = Arrangement.spacedBy(2.dp),+            ) {+                items.forEach { item ->+                    when (item) {+                        is ChatItem.DayDivider -> item(key = "day-${item.dayKey}") {+                            DayDivider(item.label)+                        }+                        is ChatItem.Msg -> item(key = item.message.id) {+                            MessageBubble(+                                msg = item.message,+                                showSender = isGroup && item.showSender,+                                isFirstInRun = item.isFirstInRun,+                                isLastInRun = item.isLastInRun,+                            )+                        }+                    }+                }+            }+        }+    }+}++/** Render units we feed to LazyColumn. */+private sealed interface ChatItem {+    data class DayDivider(+        val label: String,+        /** Unique per calendar day so the LazyColumn key won't collide+         *  on a thread that spans multiple Fridays. */+        val dayKey: Long,+    ) : ChatItem+    data class Msg(+        val message: Message,+        /** Show the sender name above this bubble (groups only). */+        val showSender: Boolean,+        /** First message in a contiguous run from the same sender —+         *  used to give the bubble a square corner at the join point. */+        val isFirstInRun: Boolean,+        val isLastInRun: Boolean,+    ) : ChatItem+}++private fun buildItems(messages: List<Message>): List<ChatItem> {+    val out = mutableListOf<ChatItem>()+    var lastDayKey: Long = Long.MIN_VALUE+    var lastSender: String? = null+    var lastDirection: MessageDirection? = null+    messages.forEachIndexed { idx, m ->+        val dayKey = startOfDayEpoch(m.timestamp)+        if (dayKey != lastDayKey) {+            out += ChatItem.DayDivider(dayLabel(m.timestamp), dayKey)+            lastDayKey = dayKey+            // Day-divider always breaks a sender run.+            lastSender = null+            lastDirection = null+        }+        val nextMessage = messages.getOrNull(idx + 1)+        val sameRunAsPrev = m.senderName == lastSender && m.direction == lastDirection+        val sameRunAsNext = nextMessage != null &&+            nextMessage.senderName == m.senderName &&+            nextMessage.direction == m.direction &&+            startOfDayEpoch(nextMessage.timestamp) == dayKey+        out += ChatItem.Msg(+            message = m,+            showSender = !sameRunAsPrev && m.direction == MessageDirection.INCOMING,+            isFirstInRun = !sameRunAsPrev,+            isLastInRun = !sameRunAsNext,+        )+        lastSender = m.senderName+        lastDirection = m.direction+    }+    return out+}++@Composable+private fun DayDivider(label: String) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .padding(vertical = 8.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        HorizontalDivider(Modifier.weight(1f))+        Text(+            label,+            modifier = Modifier.padding(horizontal = 12.dp),+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            fontSize = 12.sp,+            fontWeight = FontWeight.Medium,+        )+        HorizontalDivider(Modifier.weight(1f))+    }+}++@Composable+private fun MessageBubble(+    msg: Message,+    showSender: Boolean,+    isFirstInRun: Boolean,+    isLastInRun: Boolean,+) {+    val isOutgoing = msg.direction == MessageDirection.OUTGOING+    val bubbleColor = if (isOutgoing) MaterialTheme.colorScheme.primary+        else MaterialTheme.colorScheme.surfaceVariant+    val textColor = if (isOutgoing) MaterialTheme.colorScheme.onPrimary+        else MaterialTheme.colorScheme.onSurfaceVariant+    val alignment = if (isOutgoing) Alignment.End else Alignment.Start+    // Tail corner shrinks when this is the last bubble in a sender run.+    val corner = 18.dp+    val joinedCorner = 4.dp+    val shape = RoundedCornerShape(+        topStart = if (isOutgoing || isFirstInRun) corner else joinedCorner,+        topEnd = if (!isOutgoing || isFirstInRun) corner else joinedCorner,+        bottomStart = if (isOutgoing || isLastInRun) corner else joinedCorner,+        bottomEnd = if (!isOutgoing || isLastInRun) corner else joinedCorner,+    )++    Column(+        modifier = Modifier+            .fillMaxWidth()+            .padding(top = if (isFirstInRun) 6.dp else 0.dp),+        horizontalAlignment = alignment,+    ) {+        if (showSender && !msg.senderName.isNullOrBlank()) {+            Text(+                msg.senderName,+                modifier = Modifier.padding(start = 12.dp, bottom = 2.dp),+                fontSize = 11.sp,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                fontWeight = FontWeight.Medium,+            )+        }+        Surface(+            color = bubbleColor,+            contentColor = textColor,+            shape = shape,+            modifier = Modifier+                .widthIn(max = 320.dp)+                .heightIn(min = 32.dp),+        ) {+            Text(+                msg.body,+                modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),+                fontSize = 15.sp,+            )+        }+        ReactionsRow(msg.reactionsJson, alignToEnd = isOutgoing)+        if (isLastInRun) {+            Row(+                modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),+            ) {+                Text(+                    formatTime(msg.timestamp),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+                if (isOutgoing) {+                    val stateLabel = when (msg.state) {+                        MessageState.PENDING -> " · " + stringResource(R.string.message_state_pending)+                        MessageState.FAILED -> " · " + stringResource(R.string.message_state_failed)+                        MessageState.SENT, MessageState.DELIVERED -> ""+                    }+                    if (stateLabel.isNotEmpty()) {+                        Text(+                            stateLabel,+                            style = MaterialTheme.typography.labelSmall,+                            color = if (msg.state == MessageState.FAILED)+                                MaterialTheme.colorScheme.error+                            else MaterialTheme.colorScheme.onSurfaceVariant,+                        )+                    }+                }+            }+        }+    }+}++@Composable+private fun ReactionsRow(json: String?, alignToEnd: Boolean) {+    if (json.isNullOrBlank()) return+    val reactions = remember(json) {+        runCatching {+            Json.decodeFromString(ListSerializer(Reaction.serializer()), json)+        }.getOrNull().orEmpty()+    }+    if (reactions.isEmpty()) return+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .padding(top = 2.dp, start = 12.dp, end = 12.dp),+        horizontalArrangement = if (alignToEnd) Arrangement.End else Arrangement.Start,+    ) {+        reactions.forEach { r ->+            Surface(+                shape = RoundedCornerShape(50),+                color = MaterialTheme.colorScheme.surfaceVariant,+                contentColor = MaterialTheme.colorScheme.onSurfaceVariant,+                modifier = Modifier.padding(end = 4.dp),+            ) {+                Row(+                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp),+                    verticalAlignment = Alignment.CenterVertically,+                ) {+                    Text(r.emoji, fontSize = 13.sp)+                    if (r.count > 1) {+                        Text(+                            "  ${r.count}",+                            fontSize = 11.sp,+                            color = MaterialTheme.colorScheme.onSurfaceVariant,+                        )+                    }+                }+            }+        }+    }+}++@Composable+private fun ConvAvatar(conversation: Conversation?) {+    val photo = conversation?.avatarUrl+    val isGroup = conversation?.isGroup == true+    val name = conversation?.peerName+    Box(+        modifier = Modifier+            .size(36.dp)+            .clip(CircleShape)+            .background(MaterialTheme.colorScheme.primaryContainer),+        contentAlignment = Alignment.Center,+    ) {+        when {+            photo != null -> AsyncImage(+                model = photo,+                contentDescription = null,+                modifier = Modifier.fillMaxSize(),+                contentScale = ContentScale.Crop,+            )+            isGroup -> Text(+                "…",+                color = MaterialTheme.colorScheme.onPrimaryContainer,+                fontWeight = FontWeight.Bold,+                fontSize = 16.sp,+            )+            else -> {+                val initials = (name ?: "?").trim().take(2).uppercase()+                Text(+                    initials,+                    color = MaterialTheme.colorScheme.onPrimaryContainer,+                    fontWeight = FontWeight.SemiBold,+                )+            }+        }+    }+}++@Composable+private fun ComposeRow(+    draft: String,+    onDraftChange: (String) -> Unit,+    sending: Boolean,+    onSend: () -> Unit,+) {+    Surface(+        tonalElevation = 2.dp,+        modifier = Modifier.fillMaxWidth(),+    ) {+        Row(+            modifier = Modifier+                .padding(horizontal = 8.dp, vertical = 8.dp)+                .fillMaxWidth(),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            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))++/** Epoch-ms at the local-time start of the calendar day [ts] falls in.+ *  Unique per calendar day, used as a stable LazyColumn key. */+private fun startOfDayEpoch(ts: Long): Long {+    val cal = Calendar.getInstance().apply {+        timeInMillis = ts+        set(Calendar.HOUR_OF_DAY, 0)+        set(Calendar.MINUTE, 0)+        set(Calendar.SECOND, 0)+        set(Calendar.MILLISECOND, 0)+    }+    return cal.timeInMillis+}++/** "Today", "Yesterday", "Wednesday", or a full date for older messages. */+private fun dayLabel(ts: Long): String {+    val now = Calendar.getInstance()+    val that = Calendar.getInstance().apply { timeInMillis = ts }+    val sameDay = now.get(Calendar.YEAR) == that.get(Calendar.YEAR) &&+        now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR)+    if (sameDay) return "Today"+    val yesterday = (Calendar.getInstance()).apply { add(Calendar.DAY_OF_YEAR, -1) }+    if (yesterday.get(Calendar.YEAR) == that.get(Calendar.YEAR) &&+        yesterday.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR)+    ) return "Yesterday"+    val sixDaysAgo = (Calendar.getInstance()).apply { add(Calendar.DAY_OF_YEAR, -6) }+    if (that.after(sixDaysAgo)) {+        return SimpleDateFormat("EEEE", Locale.getDefault()).format(Date(ts))+    }+    return DateFormat.getDateInstance(DateFormat.MEDIUM).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.ktnew file mode 100644index 0000000000..4d05aa8df9--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/ui/InboxScreen.kt@@ -0,0 +1,326 @@+package com.vayunmathur.messages.ui++import androidx.compose.foundation.background as foundationBackground+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.Card+import androidx.compose.material3.CardDefaults+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.IconButton+import androidx.compose.material3.ListItem+import androidx.compose.material3.ListItemDefaults+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+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.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.messages.R+import com.vayunmathur.messages.Route+import com.vayunmathur.messages.data.Conversation+import com.vayunmathur.messages.data.MessageSource+import com.vayunmathur.messages.data.MessagesDatabase+import com.vayunmathur.messages.util.MessagesSessionManager+import com.vayunmathur.messages.util.MessagesViewModel+import com.vayunmathur.messages.gmessages.GMessagesClient+import java.text.DateFormat+import java.util.Date++/**+ * Unified inbox over conversations from both sources. Sorted by recency.+ *+ * Source is surfaced as a small chip on each row so it's always obvious+ * whether a reply will go via the user's SIM (Messages) or their Voice+ * number. We deliberately don't merge by phone number — same peer on+ * two different lines is still two threads.+ *+ * 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)+@Composable+fun InboxScreen(+    backStack: NavBackStack<Route>,+    vm: MessagesViewModel,+    db: MessagesDatabase,+) {+    val conversations by db.conversationDao().observeAll().collectAsState(initial = emptyList())+    val connectionStates by vm.connectionStates.collectAsState()++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text(stringResource(R.string.inbox_title)) },+                actions = {+                    IconButton(onClick = { backStack.add(Route.Settings) }) {+                        IconSettings()+                    }+                },+            )+        },+    ) { padding ->+        Column(+            modifier = Modifier+                .padding(padding)+                .fillMaxSize(),+        ) {+            // Setup prompt for Messages-for-Web (only source today).+            SetupPrompts(+                states = connectionStates,+                onPairMessages = { backStack.add(Route.PairMessages) },+            )++            if (conversations.isEmpty()) {+                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+                    Text(+                        stringResource(R.string.inbox_empty),+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }+            } else {+                LazyColumn {+                    items(conversations, key = { it.id }) { conv ->+                        ConversationRow(+                            conversation = conv,+                            onClick = { backStack.add(Route.Conversation(conv.id)) },+                        )+                        HorizontalDivider(Modifier.padding(horizontal = 16.dp))+                    }+                }+            }+        }+    }+}++/** Shows a source-specific setup card at the top of the inbox when the+ *  puppet is in NeedsSetup or Disconnected. */+@Composable+private fun SetupPrompts(+    states: Map<MessageSource, GMessagesClient.State>,+    onPairMessages: () -> Unit,+) {+    val msgsState = states[MessageSource.MESSAGES_WEB]+    // Show the setup card when there's no active pairing. Connected+    // and Pairing both mean "don't bug the user" (Pairing because the+    // pair screen is already up and driving the QR).+    if (msgsState !is GMessagesClient.State.Connected &&+        msgsState !is GMessagesClient.State.Pairing+    ) {+        SetupCard(+            title = stringResource(R.string.inbox_setup_messages_title),+            description = stringResource(R.string.inbox_setup_messages_desc),+            actionLabel = stringResource(R.string.inbox_setup_action),+            onAction = onPairMessages,+        )+    }+}++@Composable+private fun SetupCard(+    title: String,+    description: String,+    actionLabel: String,+    onAction: () -> Unit,+) {+    Card(+        modifier = Modifier+            .fillMaxWidth()+            .padding(horizontal = 12.dp, vertical = 6.dp)+            .clickable(onClick = onAction),+        shape = RoundedCornerShape(16.dp),+        colors = CardDefaults.cardColors(+            containerColor = MaterialTheme.colorScheme.secondaryContainer,+        ),+    ) {+        Column(Modifier.padding(16.dp)) {+            Text(title, fontWeight = FontWeight.SemiBold)+            Spacer(Modifier.height(4.dp))+            Text(+                description,+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onSecondaryContainer,+            )+            Spacer(Modifier.height(8.dp))+            Text(+                actionLabel,+                color = MaterialTheme.colorScheme.primary,+                fontWeight = FontWeight.SemiBold,+            )+        }+    }+}++@Composable+private fun ConversationRow(+    conversation: Conversation,+    onClick: () -> Unit,+) {+    ListItem(+        headlineContent = {+            Row(verticalAlignment = Alignment.CenterVertically) {+                Text(+                    conversation.peerName ?: "(unknown)",+                    fontWeight = if (conversation.unreadCount > 0) FontWeight.Bold else FontWeight.Normal,+                    modifier = Modifier.weight(1f),+                )+                Spacer(Modifier.width(8.dp))+                // SMS / RCS chip (per-conversation transport). Hidden when+                // the relay didn't tell us — most rows will have one.+                conversation.conversationType?.let { TypeChip(it) }+            }+        },+        supportingContent = {+            conversation.lastMessagePreview?.let {+                Text(it, maxLines = 1)+            }+        },+        trailingContent = {+            Column(horizontalAlignment = Alignment.End) {+                Text(+                    formatTimestamp(conversation.lastMessageTimestamp),+                    style = MaterialTheme.typography.labelSmall,+                )+                if (conversation.unreadCount > 0) {+                    Spacer(Modifier.height(4.dp))+                    UnreadBadge(conversation.unreadCount)+                }+            }+        },+        leadingContent = { Avatar(conversation.peerName, conversation.avatarUrl, conversation.isGroup) },+        modifier = Modifier.clickable(onClick = onClick),+        colors = ListItemDefaults.colors(containerColor = Color.Transparent),+    )+}++@Composable+private fun TypeChip(label: String) {+    val color = when (label) {+        "RCS" -> MaterialTheme.colorScheme.primary+        "SMS" -> MaterialTheme.colorScheme.tertiary+        else -> MaterialTheme.colorScheme.secondary+    }+    Surface(+        shape = RoundedCornerShape(8.dp),+        color = color.copy(alpha = 0.15f),+        contentColor = color,+    ) {+        Text(+            label,+            

Diff truncated.