Modern Apps git

← Modern-Apps.git

communicate: assistant provider intents (#assistant)

Commit
81c6589dd83f6b1d38b6229ac7d9f7207e4af38d
Author
Vayun Mathur <[email protected]>
When
2026-11-16 22:48 UTC (19 days ago)
Parents
62495a4
Add the provider side of the OpenAssistant messaging tools
(design /tmp/oa-design.md P3, provider side only; the
assistant-side tool registrations land separately).

Library: new com.vayunmathur.library.intents.communicate DTOs
(CommunicateData.kt), following the existing library.intents.*
source-path convention. FindConversationsQuery/ConversationData
carry threadKey as "<line>:<id>" (remote id when the line has
one, else the numeric thread id) plus address, displayName,
snippet, line and isGroup; GetMessagesQuery/ConversationMessageData
read one conversation back; SendMessageRequest/SendMessageResult
send with a typed success/error result. All fields defaulted so
older and newer callers decode each other (library DTO rule).

Communicate: FindConversationsIntent, GetMessagesIntent and
SendMessageIntent as NoDisplay AssistantIntent<In,Out> activities
copying the notes/todo pattern, exported in the manifest behind
the new signature permission
com.vayunmathur.communicate.permissions.ACCESS_COMMUNICATE.
Reads go through loadSmsThreadsMerged/loadSmsMessagesMerged
with provider-side limits (find defaults to 5, capped at 50;
messages default to 10, capped at 100, most-recent window kept
oldest-first). SendMessageIntent executes
CommunicateRepository.sendMessage for Sim/Rcs/WhatsApp/Signal
after provider-side validation of line, address and body, and
converts send failures into typed SEND_FAILED results rather
than throwing. Google Voice is excluded: it mints its bot token
in an offscreen WebView hosted by a foreground Activity, which
a NoDisplay intent cannot provide, so it returns the typed
GOOGLE_VOICE_REQUIRES_ACTIVITY error and never touches the
repository (callers fall back to opening the conversation).

A CommunicateAssistantBackend seam delegates to the real
repository in production and lets tests substitute per-line
fakes. AssistantIntentsTest covers threadKey formatting, query
filtering, limits, message windows, per-line send dispatch
(Sim/Rcs/WhatsApp/Signal), Google Voice exclusion asserted via
zero dispatched calls, provider-side validation, typed failure
on backend false/exception, and DTO default decoding.

Verified: ./gradlew :communicate:testDevUnitTest (full suite)
and :communicate:compileDevKotlin pass; the new
AssistantIntentsTest also passes in isolation. No pushes.

Diff

communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 3a7b316064..f41113b42c 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -6,6 +6,12 @@     <!-- Sensors permission at install instead of auto-granting it. -->     <uses-permission android:name="com.vayunmathur.permission.SENSORS_OPTOUT" /> +    <!-- Assistant tools (find_conversations / get_conversation_messages / send_message_v2)+         for openassistant. Signature-level: only apps signed with the Modern Apps key can call. -->+    <permission+        android:name="com.vayunmathur.communicate.permissions.ACCESS_COMMUNICATE"+        android:protectionLevel="signature" />+     <uses-permission android:name="android.permission.READ_CONTACTS" />     <uses-permission android:name="android.permission.CALL_PHONE" />     <uses-permission android:name="android.permission.READ_CALL_LOG" />@@ -135,6 +141,22 @@             </intent-filter>         </activity> +        <activity+            android:name=".intents.FindConversationsIntent"+            android:exported="true"+            android:permission="com.vayunmathur.communicate.permissions.ACCESS_COMMUNICATE"+            android:theme="@android:style/Theme.NoDisplay" />+        <activity+            android:name=".intents.GetMessagesIntent"+            android:exported="true"+            android:permission="com.vayunmathur.communicate.permissions.ACCESS_COMMUNICATE"+            android:theme="@android:style/Theme.NoDisplay" />+        <activity+            android:name=".intents.SendMessageIntent"+            android:exported="true"+            android:permission="com.vayunmathur.communicate.permissions.ACCESS_COMMUNICATE"+            android:theme="@android:style/Theme.NoDisplay" />+         <!-- Expanded conversation bubble host: must be embeddable and document-launched. -->         <activity             android:name=".notifications.BubbleActivity"
communicate/src/main/java/com/vayunmathur/communicate/intents/CommunicateAssistantBackend.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/intents/CommunicateAssistantBackend.kt b/communicate/src/main/java/com/vayunmathur/communicate/intents/CommunicateAssistantBackend.ktnew file mode 100644index 0000000000..44fd993e35--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/intents/CommunicateAssistantBackend.kt@@ -0,0 +1,178 @@+package com.vayunmathur.communicate.intents++import android.content.Context+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.LineChoice+import com.vayunmathur.communicate.data.SimManager+import com.vayunmathur.communicate.data.SmsMessage+import com.vayunmathur.communicate.data.SmsThread+import com.vayunmathur.communicate.data.loadSmsMessagesMerged+import com.vayunmathur.communicate.data.loadSmsThreadsMerged+import com.vayunmathur.communicate.data.sendMessage+import com.vayunmathur.library.intents.communicate.ConversationData+import com.vayunmathur.library.intents.communicate.ConversationMessageData+import com.vayunmathur.library.intents.communicate.FindConversationsQuery+import com.vayunmathur.library.intents.communicate.GetMessagesQuery+import com.vayunmathur.library.intents.communicate.SendMessageRequest+import com.vayunmathur.library.intents.communicate.SendMessageResult++/** Typed send-failure codes returned in [SendMessageResult.error] (never thrown). */+internal const val ERROR_GOOGLE_VOICE_REQUIRES_ACTIVITY = "GOOGLE_VOICE_REQUIRES_ACTIVITY"+internal const val ERROR_INVALID_ADDRESS = "INVALID_ADDRESS"+internal const val ERROR_INVALID_BODY = "INVALID_BODY"+internal const val ERROR_UNKNOWN_LINE = "UNKNOWN_LINE"+internal const val ERROR_SEND_FAILED = "SEND_FAILED"++internal const val DEFAULT_FIND_LIMIT = 5+internal const val MAX_FIND_LIMIT = 50+internal const val DEFAULT_MESSAGES_LIMIT = 10+internal const val MAX_MESSAGES_LIMIT = 100++/**+ * Repository seam behind the communicate assistant intents. Production delegates to+ * [CommunicateRepository]; tests install a fake per line so provider logic (filtering,+ * limits, validation, Google Voice exclusion) is asserted without telephony/network.+ */+internal interface CommunicateAssistantBackend {+    suspend fun loadThreads(context: Context): List<SmsThread>+    suspend fun loadMessages(context: Context, thread: SmsThread): List<SmsMessage>+    suspend fun send(+        context: Context,+        choice: LineChoice,+        address: String,+        body: String,+        threadRemoteId: String?,+    ): Boolean+}++internal object RealCommunicateAssistantBackend : CommunicateAssistantBackend {+    override suspend fun loadThreads(context: Context): List<SmsThread> =+        with(CommunicateRepository) { loadSmsThreadsMerged(context) }++    override suspend fun loadMessages(context: Context, thread: SmsThread): List<SmsMessage> =+        with(CommunicateRepository) { loadSmsMessagesMerged(context, thread) }++    override suspend fun send(+        context: Context,+        choice: LineChoice,+        address: String,+        body: String,+        threadRemoteId: String?,+    ): Boolean = with(CommunicateRepository) {+        sendMessage(context, choice, address, body, threadRemoteId)+    }+}++/** Test seam, mirroring the `overrideForTest` singletons elsewhere in this app. */+internal var communicateAssistantBackendForTest: CommunicateAssistantBackend? = null++internal fun communicateAssistantBackend(): CommunicateAssistantBackend =+    communicateAssistantBackendForTest ?: RealCommunicateAssistantBackend++/** `"<line>:<id>"` โ€” remote id when the line has one, else the numeric thread id. */+internal fun SmsThread.threadKey(): String =+    "${line.name}:${remoteId?.takeIf { it.isNotBlank() } ?: threadId}"++internal fun SmsThread.toConversationData(): ConversationData = ConversationData(+    threadKey = threadKey(),+    address = address,+    displayName = displayName,+    snippet = snippet,+    line = line.name,+    isGroup = isGroup,+)++internal fun SmsMessage.toConversationMessageData(): ConversationMessageData =+    ConversationMessageData(+        body = body,+        address = address,+        timestampMillis = timestampMillis,+        outgoing = outgoing,+        line = line.name,+    )++internal fun parseCommunicateLine(raw: String): CommunicateLine? {+    val normalized = raw.trim().replace(" ", "")+    if (normalized.isEmpty()) return null+    return CommunicateLine.entries.firstOrNull { it.name.equals(normalized, ignoreCase = true) }+}++internal suspend fun findConversations(+    context: Context,+    input: FindConversationsQuery,+    backend: CommunicateAssistantBackend,+): List<ConversationData> {+    val threads = runCatching { backend.loadThreads(context) }.getOrDefault(emptyList())+    val query = input.query.trim()+    val filtered = if (query.isEmpty()) {+        threads+    } else {+        threads.filter { thread ->+            thread.displayName?.contains(query, ignoreCase = true) == true ||+                thread.address.contains(query, ignoreCase = true) ||+                thread.snippet.contains(query, ignoreCase = true) ||+                thread.participants.any { it.contains(query, ignoreCase = true) }+        }+    }+    val limit = if (input.limit <= 0) DEFAULT_FIND_LIMIT else input.limit.coerceAtMost(MAX_FIND_LIMIT)+    return filtered.take(limit).map { it.toConversationData() }+}++internal suspend fun getConversationMessages(+    context: Context,+    input: GetMessagesQuery,+    backend: CommunicateAssistantBackend,+): List<ConversationMessageData> {+    val key = input.threadKey.trim()+    if (key.isEmpty() || !key.contains(':')) return emptyList()+    val threads = runCatching { backend.loadThreads(context) }.getOrDefault(emptyList())+    val thread = threads.firstOrNull { it.threadKey() == key } ?: return emptyList()+    val messages = runCatching { backend.loadMessages(context, thread) }.getOrDefault(emptyList())+    val limit = if (input.limit <= 0) {+        DEFAULT_MESSAGES_LIMIT+    } else {+        input.limit.coerceAtMost(MAX_MESSAGES_LIMIT)+    }+    // Loaders return oldest-first; keep the most recent window in that order.+    return messages.takeLast(limit).map { it.toConversationMessageData() }+}++internal suspend fun sendAssistantMessage(+    context: Context,+    input: SendMessageRequest,+    backend: CommunicateAssistantBackend,+): SendMessageResult {+    val address = input.address.trim()+    val body = input.body.trim()+    if (address.isEmpty()) return SendMessageResult(success = false, error = ERROR_INVALID_ADDRESS)+    if (body.isEmpty()) return SendMessageResult(success = false, error = ERROR_INVALID_BODY)+    val line = parseCommunicateLine(input.line)+        ?: return SendMessageResult(success = false, error = ERROR_UNKNOWN_LINE)+    // Google Voice mints its bot-defense token in an offscreen WebView hosted by a+    // foreground Activity (see CommunicateRepositorySend). A NoDisplay intent has no+    // such Activity, so this can never succeed here โ€” fail typed, never crash, and+    // never touch the repository (the caller falls back to opening the conversation).+    if (line == CommunicateLine.GoogleVoice) {+        return SendMessageResult(success = false, error = ERROR_GOOGLE_VOICE_REQUIRES_ACTIVITY)+    }+    val choice: LineChoice = when (line) {+        CommunicateLine.Sim -> runCatching { SimManager.simLineChoices(context).firstOrNull() }+            .getOrNull() ?: LineChoice.Sim(SimManager.defaultSmsSubscriptionId(), "SIM")+        CommunicateLine.Rcs -> LineChoice.Rcs+        CommunicateLine.WhatsApp -> LineChoice.WhatsApp+        CommunicateLine.Signal -> LineChoice.Signal+        CommunicateLine.GoogleVoice -> return SendMessageResult(+            success = false,+            error = ERROR_GOOGLE_VOICE_REQUIRES_ACTIVITY,+        )+    }+    val sent = runCatching {+        backend.send(context, choice, address, body, input.threadRemoteId?.takeIf { it.isNotBlank() })+    }.getOrDefault(false)+    return if (sent) {+        SendMessageResult(success = true, error = null)+    } else {+        SendMessageResult(success = false, error = ERROR_SEND_FAILED)+    }+}
communicate/src/main/java/com/vayunmathur/communicate/intents/FindConversationsIntent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/intents/FindConversationsIntent.kt b/communicate/src/main/java/com/vayunmathur/communicate/intents/FindConversationsIntent.ktnew file mode 100644index 0000000000..69fb284e52--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/intents/FindConversationsIntent.kt@@ -0,0 +1,15 @@+package com.vayunmathur.communicate.intents++import com.vayunmathur.library.intents.communicate.ConversationData+import com.vayunmathur.library.intents.communicate.FindConversationsQuery+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.ListSerializer++/** Assistant tool `find_conversations`: merged threads across all lines, newest first. */+class FindConversationsIntent : AssistantIntent<FindConversationsQuery, List<ConversationData>>(+    FindConversationsQuery.serializer(),+    ListSerializer(ConversationData.serializer()),+) {+    override suspend fun performCalculation(input: FindConversationsQuery): List<ConversationData> =+        findConversations(this, input, communicateAssistantBackend())+}
communicate/src/main/java/com/vayunmathur/communicate/intents/GetMessagesIntent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/intents/GetMessagesIntent.kt b/communicate/src/main/java/com/vayunmathur/communicate/intents/GetMessagesIntent.ktnew file mode 100644index 0000000000..8f42a2a798--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/intents/GetMessagesIntent.kt@@ -0,0 +1,17 @@+package com.vayunmathur.communicate.intents++import com.vayunmathur.library.intents.communicate.ConversationMessageData+import com.vayunmathur.library.intents.communicate.GetMessagesQuery+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.ListSerializer++/** Assistant tool `get_conversation_messages`: recent messages for a `threadKey`. */+class GetMessagesIntent : AssistantIntent<GetMessagesQuery, List<ConversationMessageData>>(+    GetMessagesQuery.serializer(),+    ListSerializer(ConversationMessageData.serializer()),+) {+    override suspend fun performCalculation(+        input: GetMessagesQuery,+    ): List<ConversationMessageData> =+        getConversationMessages(this, input, communicateAssistantBackend())+}
communicate/src/main/java/com/vayunmathur/communicate/intents/SendMessageIntent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/intents/SendMessageIntent.kt b/communicate/src/main/java/com/vayunmathur/communicate/intents/SendMessageIntent.ktnew file mode 100644index 0000000000..08797fdb3e--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/intents/SendMessageIntent.kt@@ -0,0 +1,19 @@+package com.vayunmathur.communicate.intents++import com.vayunmathur.library.intents.communicate.SendMessageRequest+import com.vayunmathur.library.intents.communicate.SendMessageResult+import com.vayunmathur.library.util.AssistantIntent++/**+ * Assistant tool `send_message_v2` (provider side). Executes+ * `CommunicateRepository.sendMessage` for Sim/Rcs/WhatsApp/Signal. Google Voice+ * needs a foreground Activity for its bot-token mint, so it returns the typed+ * [ERROR_GOOGLE_VOICE_REQUIRES_ACTIVITY] result instead of attempting a send.+ */+class SendMessageIntent : AssistantIntent<SendMessageRequest, SendMessageResult>(+    SendMessageRequest.serializer(),+    SendMessageResult.serializer(),+) {+    override suspend fun performCalculation(input: SendMessageRequest): SendMessageResult =+        sendAssistantMessage(this, input, communicateAssistantBackend())+}
communicate/src/test/java/com/vayunmathur/communicate/intents/AssistantIntentsTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/intents/AssistantIntentsTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/intents/AssistantIntentsTest.ktnew file mode 100644index 0000000000..efcf034c9f--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/intents/AssistantIntentsTest.kt@@ -0,0 +1,305 @@+package com.vayunmathur.communicate.intents++import android.content.Context+import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.LineChoice+import com.vayunmathur.communicate.data.SmsMessage+import com.vayunmathur.communicate.data.SmsThread+import com.vayunmathur.library.intents.communicate.FindConversationsQuery+import com.vayunmathur.library.intents.communicate.GetMessagesQuery+import com.vayunmathur.library.intents.communicate.SendMessageRequest+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Assistant-tool ([FindConversationsIntent]/[GetMessagesIntent]/[SendMessageIntent])+ * provider logic against a fake [CommunicateAssistantBackend] installed per test,+ * one fake behaviour per line โ€” mirroring todo's AssistantIntentsTest shape.+ * Telephony/network/repository internals are not exercised here.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class AssistantIntentsTest {++    private class FakeBackend(+        val threads: List<SmsThread> = emptyList(),+        val messages: Map<String, List<SmsMessage>> = emptyMap(),+        var sendResult: Boolean = true,+        var sendFailure: Throwable? = null,+    ) : CommunicateAssistantBackend {+        data class SentCall(+            val category: CommunicateLine,+            val address: String,+            val body: String,+            val threadRemoteId: String?,+        )++        val sentCalls = mutableListOf<SentCall>()++        override suspend fun loadThreads(context: Context): List<SmsThread> = threads++        override suspend fun loadMessages(context: Context, thread: SmsThread): List<SmsMessage> =+            messages[thread.threadKey()].orEmpty()++        override suspend fun send(+            context: Context,+            choice: LineChoice,+            address: String,+            body: String,+            threadRemoteId: String?,+        ): Boolean {+            sendFailure?.let { throw it }+            sentCalls += SentCall(choice.category, address, body, threadRemoteId)+            return sendResult+        }+    }++    private fun thread(+        line: CommunicateLine,+        threadId: Long = 1L,+        remoteId: String? = null,+        address: String = "+14155550101",+        displayName: String? = null,+        snippet: String = "",+        isGroup: Boolean = false,+        timestamp: Long = 0L,+    ) = SmsThread(+        threadId = threadId,+        address = address,+        displayName = displayName,+        snippet = snippet,+        timestampMillis = timestamp,+        unreadCount = 0,+        line = line,+        remoteId = remoteId,+        isGroup = isGroup,+    )++    private fun message(body: String, ts: Long, outgoing: Boolean = false, line: CommunicateLine = CommunicateLine.Sim) =+        SmsMessage(+            id = ts,+            threadId = 1L,+            address = "+14155550101",+            body = body,+            timestampMillis = ts,+            outgoing = outgoing,+            read = true,+            line = line,+        )++    private val simThread = thread(+        CommunicateLine.Sim, threadId = 42, address = "+14155550101",+        displayName = "Alice", snippet = "see you soon", timestamp = 300,+    )+    private val waThread = thread(+        CommunicateLine.WhatsApp, threadId = 7, remoteId = "[email protected]",+        address = "+14155550102", displayName = "Bob", snippet = "photo", timestamp = 200,+    )+    private val waGroup = thread(+        CommunicateLine.WhatsApp, threadId = 8, remoteId = "[email protected]",+        address = "[email protected]", displayName = "Family", snippet = "dinner?", isGroup = true, timestamp = 150,+    )+    private val gvThread = thread(+        CommunicateLine.GoogleVoice, threadId = 9, remoteId = "t.abc123",+        address = "+14155550103", displayName = "Carol", snippet = "gv hello", timestamp = 100,+    )++    private var fake = FakeBackend()++    @BeforeTest+    fun setUp() {+        fake = FakeBackend(threads = listOf(simThread, waThread, waGroup, gvThread))+        communicateAssistantBackendForTest = fake+    }++    @AfterTest+    fun tearDown() {+        communicateAssistantBackendForTest = null+    }++    // --- FindConversationsIntent ---++    @Test+    fun findBlankQueryReturnsAllWithThreadKeys() = runBlocking {+        val out = FindConversationsIntent().performCalculation(FindConversationsQuery())+        assertEquals(+            listOf("Sim:42", "WhatsApp:[email protected]", "WhatsApp:[email protected]", "GoogleVoice:t.abc123"),+            out.map { it.threadKey },+        )+        assertEquals("Alice", out[0].displayName)+        assertEquals("+14155550101", out[0].address)+        assertEquals("see you soon", out[0].snippet)+        assertEquals("Sim", out[0].line)+        assertFalse(out[0].isGroup)+        assertTrue(out[2].isGroup)+        assertEquals("WhatsApp", out[2].line)+    }++    @Test+    fun findQueryFiltersNameAddressAndSnippetCaseInsensitively() = runBlocking {+        val byName = FindConversationsIntent().performCalculation(FindConversationsQuery(query = "alice"))+        assertEquals(listOf("Sim:42"), byName.map { it.threadKey })+        val byAddress = FindConversationsIntent().performCalculation(FindConversationsQuery(query = "5550102"))+        assertEquals(listOf("WhatsApp:[email protected]"), byAddress.map { it.threadKey })+        val bySnippet = FindConversationsIntent().performCalculation(FindConversationsQuery(query = "DINNER"))+        assertEquals(listOf("WhatsApp:[email protected]"), bySnippet.map { it.threadKey })+        assertTrue(+            FindConversationsIntent().performCalculation(FindConversationsQuery(query = "nobody")).isEmpty(),+        )+    }++    @Test+    fun findLimitCapsAndNonPositiveDefaults() = runBlocking {+        assertEquals(+            2,+            FindConversationsIntent().performCalculation(FindConversationsQuery(limit = 2)).size,+        )+        // limit <= 0 falls back to the DTO default window (5), so all 4 seeded rows return.+        assertEquals(+            4,+            FindConversationsIntent().performCalculation(FindConversationsQuery(limit = 0)).size,+        )+        assertEquals(+            4,+            FindConversationsIntent().performCalculation(FindConversationsQuery(limit = 500)).size,+        )+    }++    // --- GetMessagesIntent ---++    @Test+    fun getMessagesReturnsMostRecentWindowOldestFirst() = runBlocking {+        fake = FakeBackend(+            threads = listOf(simThread),+            messages = mapOf(+                "Sim:42" to listOf(+                    message("one", 1), message("two", 2, outgoing = true), message("three", 3),+                ),+            ),+        ).also { communicateAssistantBackendForTest = it }+        val out = GetMessagesIntent().performCalculation(GetMessagesQuery(threadKey = "Sim:42", limit = 2))+        assertEquals(listOf("two", "three"), out.map { it.body })+        assertTrue(out[0].outgoing)+        assertEquals("Sim", out[0].line)+        assertEquals(2L, out[0].timestampMillis)+        val all = GetMessagesIntent().performCalculation(GetMessagesQuery(threadKey = "Sim:42"))+        assertEquals(listOf("one", "two", "three"), all.map { it.body })+    }++    @Test+    fun getMessagesUnknownOrMalformedKeyReturnsEmpty() = runBlocking {+        assertTrue(GetMessagesIntent().performCalculation(GetMessagesQuery(threadKey = "Sim:999")).isEmpty())+        assertTrue(GetMessagesIntent().performCalculation(GetMessagesQuery(threadKey = "not-a-key")).isEmpty())+        assertTrue(GetMessagesIntent().performCalculation(GetMessagesQuery(threadKey = "")).isEmpty())+        // Remote-id keys resolve too (WhatsApp JID contains no extra colon handling surprises).+        assertTrue(+            GetMessagesIntent().performCalculation(+                GetMessagesQuery(threadKey = "WhatsApp:[email protected]"),+            ).isEmpty(),+        )+    }++    // --- SendMessageIntent: one case per line ---++    @Test+    fun sendOnSimRcsWhatsAppSignalDispatchesPerLine() = runBlocking {+        for ((rawLine, expected) in listOf(+            "Sim" to CommunicateLine.Sim,+            "Rcs" to CommunicateLine.Rcs,+            "WhatsApp" to CommunicateLine.WhatsApp,+            "Signal" to CommunicateLine.Signal,+        )) {+            fake.sentCalls.clear()+            val result = SendMessageIntent().performCalculation(+                SendMessageRequest(address = "+14155550101", line = rawLine, body = "hello"),+            )+            assertTrue(result.success, "expected success for $rawLine, got $result")+            assertNull(result.error)+            assertEquals(1, fake.sentCalls.size)+            assertEquals(expected, fake.sentCalls.single().category)+            assertEquals("+14155550101", fake.sentCalls.single().address)+            assertEquals("hello", fake.sentCalls.single().body)+        }+        // Line names parse case-insensitively and threadRemoteId passes through.+        fake.sentCalls.clear()+        val wa = SendMessageIntent().performCalculation(+            SendMessageRequest(+                address = "+14155550102", line = "whatsapp", body = "hi",+                threadRemoteId = "[email protected]",+            ),+        )+        assertTrue(wa.success)+        assertEquals("[email protected]", fake.sentCalls.single().threadRemoteId)+    }++    @Test+    fun sendOnGoogleVoiceReturnsTypedErrorAndNeverDispatches() = runBlocking {+        val result = SendMessageIntent().performCalculation(+            SendMessageRequest(address = "+14155550103", line = "GoogleVoice", body = "hello"),+        )+        assertFalse(result.success)+        assertEquals(ERROR_GOOGLE_VOICE_REQUIRES_ACTIVITY, result.error)+        assertTrue(fake.sentCalls.isEmpty(), "GV must be excluded before the repository is touched")+    }++    @Test+    fun sendValidatesAddressBodyAndLineProviderSide() = runBlocking {+        val noAddress = SendMessageIntent().performCalculation(+            SendMessageRequest(address = "  ", line = "Sim", body = "hi"),+        )+        assertEquals(ERROR_INVALID_ADDRESS, noAddress.error)+        val noBody = SendMessageIntent().performCalculation(+            SendMessageRequest(address = "+14155550101", line = "Sim", body = " "),+        )+        assertEquals(ERROR_INVALID_BODY, noBody.error)+        val badLine = SendMessageIntent().performCalculation(+            SendMessageRequest(address = "+14155550101", line = "Telegram", body = "hi"),+        )+        assertEquals(ERROR_UNKNOWN_LINE, badLine.error)+        assertFalse(noAddress.success)+        assertFalse(noBody.success)+        assertFalse(badLine.success)+        assertTrue(fake.sentCalls.isEmpty())+    }++    @Test+    fun sendFailureAndExceptionBecomeTypedSendFailed() = runBlocking {+        fake.sendResult = false+        val failed = SendMessageIntent().performCalculation(+            SendMessageRequest(address = "+14155550101", line = "Signal", body = "hi"),+        )+        assertEquals(false to ERROR_SEND_FAILED, failed.toPair())+        fake.sendFailure = RuntimeException("boom")+        val crashed = SendMessageIntent().performCalculation(+            SendMessageRequest(address = "+14155550101", line = "Signal", body = "hi"),+        )+        assertFalse(crashed.success)+        assertEquals(ERROR_SEND_FAILED, crashed.error)+    }++    // --- DTO compat ---++    @Test+    fun dtoDefaultsDecodeFromEmptyJson() {+        val send = Json.decodeFromString(SendMessageRequest.serializer(), "{}")+        assertEquals(SendMessageRequest(), send)+        val find = Json.decodeFromString(FindConversationsQuery.serializer(), "{}")+        assertEquals("", find.query)+        assertEquals(5, find.limit)+        val get = Json.decodeFromString(GetMessagesQuery.serializer(), "{}")+        assertEquals(10, get.limit)+    }++    private fun com.vayunmathur.library.intents.communicate.SendMessageResult.toPair() =+        success to error+}
library/src/main/java/com/vayunmathur/library/intents/communicate/CommunicateData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/communicate/CommunicateData.kt b/library/src/main/java/com/vayunmathur/library/intents/communicate/CommunicateData.ktnew file mode 100644index 0000000000..557c0567f7--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/communicate/CommunicateData.kt@@ -0,0 +1,80 @@+package com.vayunmathur.library.intents.communicate++import kotlinx.serialization.Serializable++/**+ * Shared wire DTOs for communicate's cross-app assistant intents+ * ([com.vayunmathur.library.util.AssistantIntent]): `FindConversationsIntent`,+ * `GetMessagesIntent` and `SendMessageIntent` in `com.vayunmathur.communicate.intents`,+ * answered only for a co-signed caller behind+ * `com.vayunmathur.communicate.permissions.ACCESS_COMMUNICATE`.+ *+ * Thin and UI-free by design: line is the `CommunicateLine` name (`Sim`, `GoogleVoice`,+ * `WhatsApp`, `Signal`, `Rcs`) as a plain string so this package never depends on the+ * communicate app's own types. Every field has a default so older/newer callers can+ * omit fields without breaking decode (library DTO-compat rule).+ */++/** Find conversations whose name, address or snippet contains [query] (blank = all). */+@Serializable+data class FindConversationsQuery(+    val query: String = "",+    val limit: Int = 5,+)++/**+ * One conversation as the assistant sees it.+ *+ * @property threadKey stable key `"<line>:<id>"` (e.g. `Sim:42`, `WhatsApp:[email protected]`,+ * `GoogleVoice:t.<id>`); hand it back verbatim to [GetMessagesQuery].+ */+@Serializable+data class ConversationData(+    val threadKey: String = "",+    val address: String = "",+    val displayName: String? = null,+    val snippet: String = "",+    val line: String = "",+    val isGroup: Boolean = false,+)++/** Read the messages of the conversation identified by [threadKey]. */+@Serializable+data class GetMessagesQuery(+    val threadKey: String = "",+    val limit: Int = 10,+)++/** One message in a conversation, oldest-first within the returned window. */+@Serializable+data class ConversationMessageData(+    val body: String = "",+    val address: String = "",+    val timestampMillis: Long = 0L,+    val outgoing: Boolean = false,+    val line: String = "",+)++/**+ * Send [body] to [address] on [line]. [threadRemoteId] is the provider-side thread /+ * conversation id (WhatsApp JID, Signal recipient, RCS/GV thread id) when replying to+ * an existing conversation; null starts (or resolves) a 1:1 from [address] alone.+ */+@Serializable+data class SendMessageRequest(+    val address: String = "",+    val line: String = "",+    val body: String = "",+    val threadRemoteId: String? = null,+)++/**+ * Outcome of a [SendMessageRequest]. Failures are typed results, never exceptions:+ * [error] is a stable machine-readable code (e.g. `GOOGLE_VOICE_REQUIRES_ACTIVITY`,+ * `INVALID_ADDRESS`, `INVALID_BODY`, `UNKNOWN_LINE`, `SEND_FAILED`).+ */+@Serializable+data class SendMessageResult(+    val success: Boolean = false,+    val error: String? = null,+)