From b702b6e75b2db45854c094bc7175023a8c6c1a77 Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Mon, 16 Nov 2026 18:09:04 +0000 Subject: [PATCH 1/9] dynamic function and runtime gating, added register/unregister instead of declaring, disabled function default converted to dynamic toggle --- .../chatapp/AppFunctionsViewModelTest.kt | 68 +++++ .../AppFunctionInstrumentationTest.kt | 270 ++++++++++++++++++ .../example/chatapp/AppFunctionsViewModel.kt | 121 ++++++++ .../BaseChatAppFunctionService.kt | 27 +- 4 files changed, 480 insertions(+), 6 deletions(-) diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt index 9be2bd64..bab92e49 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt @@ -18,6 +18,7 @@ package com.example.chatapp import android.app.Application import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.SdkSuppress import com.example.chatapp.appfunctions.ChatAppFunctionService import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest @@ -58,4 +59,71 @@ class AppFunctionsViewModelTest { val state = viewModel.uiState.first() assertNotNull(state) } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun registerSearchContacts_enablesFunction() = + runTest { + viewModel.registerSearchContacts() + val state = viewModel.uiState.value + assertNotNull(state) + } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun onUserAuthStateChanged_togglesRegistration() = + runTest { + viewModel.onUserAuthStateChanged(isSignedIn = true) + var state = viewModel.uiState.value + assertNotNull(state) + + viewModel.onUserAuthStateChanged(isSignedIn = false) + state = viewModel.uiState.value + assertNotNull(state) + } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun registerFetchSendMessageDetails_enablesFunction() = + runTest { + viewModel.registerFetchSendMessageDetails() + val state = viewModel.uiState.value + assertNotNull(state) + } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun registerSendMessage_enablesFunction() = + runTest { + viewModel.registerSendMessage() + val state = viewModel.uiState.value + assertNotNull(state) + } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun registerMakeCall_enablesFunction() = + runTest { + viewModel.registerMakeCall() + val state = viewModel.uiState.value + assertNotNull(state) + } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun registerUpdateChatWallpaper_enablesFunction() = + runTest { + viewModel.registerUpdateChatWallpaper() + val state = viewModel.uiState.value + assertNotNull(state) + } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun registerSearchMessages_enablesFunction() = + runTest { + viewModel.registerSearchMessages() + val state = viewModel.uiState.value + assertNotNull(state) + } } diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt index 2a0d5219..2376ec63 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt @@ -63,6 +63,10 @@ class AppFunctionInstrumentationTest { @Test fun testSend_success() = runBlocking { + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) val sendMessageFunctionMetadata = appFunctionManager .searchAppFunctions( @@ -99,6 +103,10 @@ class AppFunctionInstrumentationTest { @Test fun testSend_emptyContent_fails() = runBlocking { + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) val sendMessageFunctionMetadata = appFunctionManager .searchAppFunctions( @@ -128,6 +136,10 @@ class AppFunctionInstrumentationTest { @Test fun testSearchContacts_success() = runBlocking { + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) val getRecipientsFunctionMetadata = appFunctionManager .searchAppFunctions( @@ -166,4 +178,262 @@ class AppFunctionInstrumentationTest { ), ) } + + @Test + fun testSearchContacts_disabledByDefault() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS } + val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + val searchContactsState = states.singleOrNull { it.functionName == metadata.name } + assertThat(searchContactsState?.isEnabled ?: false).isFalse() + } + + @Test + fun testSearchContacts_registrationLifecycle() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS } + + // 1. Enable / Register capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + var searchContactsState = states.singleOrNull { it.functionName == metadata.name } + assertThat(searchContactsState?.isEnabled).isTrue() + + // 2. Disable / Unregister capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, + AppFunctionManager.APP_FUNCTION_STATE_DISABLED, + ) + states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + searchContactsState = states.singleOrNull { it.functionName == metadata.name } + assertThat(searchContactsState?.isEnabled).isFalse() + } + + @Test + fun testFetchSendMessageDetails_disabledByDefault() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS } + val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + val functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled ?: false).isFalse() + } + + @Test + fun testFetchSendMessageDetails_registrationLifecycle() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS } + + // 1. Enable / Register capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + var functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isTrue() + + // 2. Disable / Unregister capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, + AppFunctionManager.APP_FUNCTION_STATE_DISABLED, + ) + states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isFalse() + } + + @Test + fun testSendMessage_disabledByDefault() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE } + val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + val functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled ?: false).isFalse() + } + + @Test + fun testSendMessage_registrationLifecycle() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE } + + // 1. Enable / Register capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + var functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isTrue() + + // 2. Disable / Unregister capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_DISABLED, + ) + states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isFalse() + } + + @Test + fun testMakeCall_disabledByDefault() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_MAKE_CALL } + val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + val functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled ?: false).isFalse() + } + + @Test + fun testMakeCall_registrationLifecycle() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_MAKE_CALL } + + // 1. Enable / Register capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_MAKE_CALL, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + var functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isTrue() + + // 2. Disable / Unregister capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_MAKE_CALL, + AppFunctionManager.APP_FUNCTION_STATE_DISABLED, + ) + states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isFalse() + } + + @Test + fun testUpdateChatWallpaper_disabledByDefault() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER } + val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + val functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled ?: false).isFalse() + } + + @Test + fun testUpdateChatWallpaper_registrationLifecycle() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER } + + // 1. Enable / Register capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + var functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isTrue() + + // 2. Disable / Unregister capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, + AppFunctionManager.APP_FUNCTION_STATE_DISABLED, + ) + states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isFalse() + } + + @Test + fun testSearchMessages_disabledByDefault() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES } + val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + val functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled ?: false).isFalse() + } + + @Test + fun testSearchMessages_registrationLifecycle() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES } + + // 1. Enable / Register capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + var functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isTrue() + + // 2. Disable / Unregister capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, + AppFunctionManager.APP_FUNCTION_STATE_DISABLED, + ) + states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isFalse() + } } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt index c32de53f..90c57700 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt @@ -16,8 +16,10 @@ package com.example.chatapp import android.app.Application +import androidx.annotation.RequiresApi import androidx.appfunctions.AppFunctionManager import androidx.appfunctions.AppFunctionSearchSpec +import com.example.chatapp.appfunctions.BaseChatAppFunctionService import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel @@ -122,4 +124,123 @@ class AppFunctionsViewModel appFunctionManager?.setAppFunctionEnabled(id, newState) } } + + /** + * Registers (enables) the searchContacts capability with the OS at runtime. + */ + @RequiresApi(36) + fun registerSearchContacts() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, enabled = true) + } + + /** + * Unregisters (disables) the searchContacts capability with the OS at runtime. + */ + @RequiresApi(36) + fun unregisterSearchContacts() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, enabled = false) + } + + /** + * Registers (enables) the fetchSendMessageDetails capability with the OS at runtime. + */ + @RequiresApi(36) + fun registerFetchSendMessageDetails() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, enabled = true) + } + + /** + * Unregisters (disables) the fetchSendMessageDetails capability with the OS at runtime. + */ + @RequiresApi(36) + fun unregisterFetchSendMessageDetails() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, enabled = false) + } + + /** + * Registers (enables) the sendMessage capability with the OS at runtime. + */ + @RequiresApi(36) + fun registerSendMessage() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, enabled = true) + } + + /** + * Unregisters (disables) the sendMessage capability with the OS at runtime. + */ + @RequiresApi(36) + fun unregisterSendMessage() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, enabled = false) + } + + /** + * Registers (enables) the makeCall capability with the OS at runtime. + */ + @RequiresApi(36) + fun registerMakeCall() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_MAKE_CALL, enabled = true) + } + + /** + * Unregisters (disables) the makeCall capability with the OS at runtime. + */ + @RequiresApi(36) + fun unregisterMakeCall() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_MAKE_CALL, enabled = false) + } + + /** + * Registers (enables) the updateChatWallpaper capability with the OS at runtime. + */ + @RequiresApi(36) + fun registerUpdateChatWallpaper() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, enabled = true) + } + + /** + * Unregisters (disables) the updateChatWallpaper capability with the OS at runtime. + */ + @RequiresApi(36) + fun unregisterUpdateChatWallpaper() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, enabled = false) + } + + /** + * Registers (enables) the searchMessages capability with the OS at runtime. + */ + @RequiresApi(36) + fun registerSearchMessages() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, enabled = true) + } + + /** + * Unregisters (disables) the searchMessages capability with the OS at runtime. + */ + @RequiresApi(36) + fun unregisterSearchMessages() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, enabled = false) + } + + /** + * Handles user authentication state changes to dynamically register or unregister + * app capabilities with the OS at runtime. + */ + @RequiresApi(36) + fun onUserAuthStateChanged(isSignedIn: Boolean) { + if (isSignedIn) { + registerSearchContacts() + registerFetchSendMessageDetails() + registerSendMessage() + registerMakeCall() + registerUpdateChatWallpaper() + registerSearchMessages() + } else { + unregisterSearchContacts() + unregisterFetchSendMessageDetails() + unregisterSendMessage() + unregisterMakeCall() + unregisterUpdateChatWallpaper() + unregisterSearchMessages() + } + } } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt index 1e53c184..5466e5d4 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt @@ -67,7 +67,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @return List of [ContactSearchResult] objects matching the query. * @throws AppFunctionInvalidArgumentException If query is empty or blank, an invalid contactType is provided, or if no matching contact or group is found. If thrown, suggest the user clarify the recipient or group name. */ - @AppFunctionDeclaration(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun searchContacts( query: String, @AppFunctionStringValueConstraint(enumValues = ["INDIVIDUAL", "GROUP", "ANY"]) @@ -121,7 +121,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @throws AppFunctionElementNotFoundException If no contact or group matches endpointValue. If thrown, call "searchContacts" to find the correct ID. */ @OptIn(ExperimentalAppFunctionsApi::class) - @AppFunctionDeclaration(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun fetchSendMessageDetails( endpointValue: String, messageBody: String, @@ -202,7 +202,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @throws AppFunctionElementNotFoundException If no contact or group matches endpointValue. If thrown, call "searchContacts" to find the correct ID. * @throws AppFunctionAppUnknownException If sending fails due to a repository error. If thrown, suggest the user retry later. */ - @AppFunctionDeclaration(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun sendMessage( endpointValue: String, messageBody: String, @@ -241,7 +241,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @return A [PendingIntent] that launches the call activity in the application UI. * @throws AppFunctionElementNotFoundException If no recipient exists for endpointValue. If thrown, call "searchContacts" to find the correct ID. */ - @AppFunctionDeclaration(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun makeCall(endpointValue: String): PendingIntent { val recipient = recipientsRepository.getRecipientById(endpointValue) @@ -266,7 +266,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @param chatId The unique identifier for the recipient or chat group. * @param wallpaperUri The URI of the image file to set as the chat wallpaper. */ - @AppFunctionDeclaration(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun updateChatWallpaper( chatId: String, wallpaperUri: Uri, @@ -295,7 +295,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @return List of [MessagesSearchResult] matching the query. * @throws AppFunctionInvalidArgumentException If the query is blank. */ - @AppFunctionDeclaration(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun searchMessages( query: String, endpointValue: String? = null, @@ -365,4 +365,19 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { "Me" } } + + companion object { + const val FUNCTION_ID_SEARCH_CONTACTS = + "com.example.chatapp.appfunctions.ChatAppFunctionService#searchContacts" + const val FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS = + "com.example.chatapp.appfunctions.ChatAppFunctionService#fetchSendMessageDetails" + const val FUNCTION_ID_SEND_MESSAGE = + "com.example.chatapp.appfunctions.ChatAppFunctionService#sendMessage" + const val FUNCTION_ID_MAKE_CALL = + "com.example.chatapp.appfunctions.ChatAppFunctionService#makeCall" + const val FUNCTION_ID_UPDATE_CHAT_WALLPAPER = + "com.example.chatapp.appfunctions.ChatAppFunctionService#updateChatWallpaper" + const val FUNCTION_ID_SEARCH_MESSAGES = + "com.example.chatapp.appfunctions.ChatAppFunctionService#searchMessages" + } } From 36c7e23df6c484242e209e18e7ed34ee540a58ea Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Wed, 18 Nov 2026 17:35:41 +0000 Subject: [PATCH 2/9] dynamic function and runtime gating, added register/unregister instead of declaring, disabled function default converted to dynamic toggle --- .../main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt index 90c57700..6e506c37 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt @@ -19,9 +19,9 @@ import android.app.Application import androidx.annotation.RequiresApi import androidx.appfunctions.AppFunctionManager import androidx.appfunctions.AppFunctionSearchSpec -import com.example.chatapp.appfunctions.BaseChatAppFunctionService import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope +import com.example.chatapp.appfunctions.BaseChatAppFunctionService import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted From a308eba83418475974f604745dec980b7151e591 Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Wed, 18 Nov 2026 22:28:53 +0000 Subject: [PATCH 3/9] setup app-private access and self helpers --- .../chatapp/AppFunctionsViewModelTest.kt | 9 +++++ .../AppFunctionInstrumentationTest.kt | 33 +++++++++++++++++ .../example/chatapp/AppFunctionsViewModel.kt | 36 +++++++++++++++++++ 3 files changed, 78 insertions(+) diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt index bab92e49..cae0cc4d 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt @@ -126,4 +126,13 @@ class AppFunctionsViewModelTest { val state = viewModel.uiState.value assertNotNull(state) } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun invokeFetchSendMessageDetailsInternally_executesSuccessfully() = + runTest { + viewModel.registerFetchSendMessageDetails() + val result = viewModel.invokeFetchSendMessageDetailsInternally("1", "Test Preview") + assertNotNull(result) + } } diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt index 2376ec63..11b09ba0 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt @@ -436,4 +436,37 @@ class AppFunctionInstrumentationTest { functionState = states.singleOrNull { it.functionName == metadata.name } assertThat(functionState?.isEnabled).isFalse() } + + @Test + fun testFetchSendMessageDetails_selfInvocation() = + runBlocking { + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS } + + val testRecipient = recipientsRepository.getAllRecipients().first() + val request = + ExecuteAppFunctionRequest( + targetPackageName = context.packageName, + ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, + AppFunctionData.Builder( + metadata.parameters, + metadata.components, + ) + .setString("endpointValue", testRecipient.id) + .setString("messageBody", "Test Preview") + .build(), + ) + + val response = appFunctionManager.executeAppFunction(request) + val successResponse = assertIs(response) + assertThat(successResponse).isNotNull() + } } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt index 6e506c37..dbc772eb 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt @@ -17,8 +17,11 @@ package com.example.chatapp import android.app.Application import androidx.annotation.RequiresApi +import androidx.appfunctions.AppFunctionData import androidx.appfunctions.AppFunctionManager import androidx.appfunctions.AppFunctionSearchSpec +import androidx.appfunctions.ExecuteAppFunctionRequest +import androidx.appfunctions.ExecuteAppFunctionResponse import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.example.chatapp.appfunctions.BaseChatAppFunctionService @@ -243,4 +246,37 @@ class AppFunctionsViewModel unregisterSearchMessages() } } + + /** + * Invokes the app-private fetchSendMessageDetails AppFunction internally from within ChatApp. + * + * @param endpointValue The recipient or group identifier. + * @param messageBody The text message body. + * @return The execution response from AppFunctionManager. + */ + @RequiresApi(36) + suspend fun invokeFetchSendMessageDetailsInternally( + endpointValue: String, + messageBody: String, + ): ExecuteAppFunctionResponse? { + if (appFunctionManager == null) return null + val packageName = getApplication().packageName + val searchSpec = AppFunctionSearchSpec(packageNames = setOf(packageName)) + val metadata = + appFunctionManager.searchAppFunctions(searchSpec) + .singleOrNull { it.id == BaseChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS } + ?: return null + + val request = + ExecuteAppFunctionRequest( + targetPackageName = packageName, + BaseChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, + AppFunctionData.Builder(metadata.parameters, metadata.components) + .setString("endpointValue", endpointValue) + .setString("messageBody", messageBody) + .build(), + ) + + return appFunctionManager.executeAppFunction(request) + } } From 6ff84a3700d82de56d516e030feedc8b547e2e98 Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Fri, 20 Nov 2026 16:41:54 +0000 Subject: [PATCH 4/9] implemented reviewSendMessage returning PendingIntent to open chat with draft --- .../chatapp/AppFunctionsViewModelTest.kt | 9 +++ .../AppFunctionInstrumentationTest.kt | 76 +++++++++++++++++++ .../example/chatapp/AppFunctionsViewModel.kt | 18 +++++ .../BaseChatAppFunctionService.kt | 29 +++++++ 4 files changed, 132 insertions(+) diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt index cae0cc4d..18e3896e 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt @@ -135,4 +135,13 @@ class AppFunctionsViewModelTest { val result = viewModel.invokeFetchSendMessageDetailsInternally("1", "Test Preview") assertNotNull(result) } + + @Test + @SdkSuppress(minSdkVersion = 36) + fun registerReviewSendMessage_enablesFunction() = + runTest { + viewModel.registerReviewSendMessage() + val state = viewModel.uiState.value + assertNotNull(state) + } } diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt index 11b09ba0..b2de13a9 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt @@ -469,4 +469,80 @@ class AppFunctionInstrumentationTest { val successResponse = assertIs(response) assertThat(successResponse).isNotNull() } + + @Test + fun testReviewSendMessage_disabledByDefault() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE } + val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + val functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled ?: false).isFalse() + } + + @Test + fun testReviewSendMessage_registrationLifecycle() = + runBlocking { + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE } + + // 1. Enable / Register capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + var functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isTrue() + + // 2. Disable / Unregister capability + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_DISABLED, + ) + states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) + functionState = states.singleOrNull { it.functionName == metadata.name } + assertThat(functionState?.isEnabled).isFalse() + } + + @Test + fun testReviewSendMessage_returnsImmutablePendingIntent() = + runBlocking { + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + val metadata = + appFunctionManager + .searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + .single { it.id == ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE } + + val testRecipient = recipientsRepository.getAllRecipients().first() + val request = + ExecuteAppFunctionRequest( + targetPackageName = context.packageName, + ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, + AppFunctionData.Builder( + metadata.parameters, + metadata.components, + ) + .setString("endpointValue", testRecipient.id) + .setString("messageBody", "Draft message for review") + .build(), + ) + + val response = appFunctionManager.executeAppFunction(request) + val successResponse = assertIs(response) + assertThat(successResponse).isNotNull() + } } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt index dbc772eb..f44e11ac 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt @@ -224,6 +224,22 @@ class AppFunctionsViewModel toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, enabled = false) } + /** + * Registers (enables) the reviewSendMessage capability with the OS at runtime. + */ + @RequiresApi(36) + fun registerReviewSendMessage() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, enabled = true) + } + + /** + * Unregisters (disables) the reviewSendMessage capability with the OS at runtime. + */ + @RequiresApi(36) + fun unregisterReviewSendMessage() { + toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, enabled = false) + } + /** * Handles user authentication state changes to dynamically register or unregister * app capabilities with the OS at runtime. @@ -237,6 +253,7 @@ class AppFunctionsViewModel registerMakeCall() registerUpdateChatWallpaper() registerSearchMessages() + registerReviewSendMessage() } else { unregisterSearchContacts() unregisterFetchSendMessageDetails() @@ -244,6 +261,7 @@ class AppFunctionsViewModel unregisterMakeCall() unregisterUpdateChatWallpaper() unregisterSearchMessages() + unregisterReviewSendMessage() } } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt index 5466e5d4..8c349d00 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt @@ -233,6 +233,33 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { return "Message sent to: $displayName." } + /** Prepares message for review, returns PendingIntent to open chat with draft. */ + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + suspend fun reviewSendMessage( + endpointValue: String, + messageBody: String, + ): PendingIntent { + val recipientId = + recipientsRepository.getRecipientById(endpointValue)?.id + ?: recipientsRepository.getGroupById(endpointValue)?.id + ?: throw AppFunctionElementNotFoundException( + "No contact or group found for endpointValue: $endpointValue", + ) + + val intent = + Intent().setClassName(this, "com.example.chatapp.MainActivity").apply { + putExtra("nav_route", "chat/$recipientId?draft=${Uri.encode(messageBody)}") + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) + } + + return PendingIntent.getActivity( + this, + 0, + intent, + PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, + ) + } + /** * Initiate a voice call with an individual contact or group. * Required workflow: Call "searchContacts" first to obtain a valid endpointValue. @@ -379,5 +406,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { "com.example.chatapp.appfunctions.ChatAppFunctionService#updateChatWallpaper" const val FUNCTION_ID_SEARCH_MESSAGES = "com.example.chatapp.appfunctions.ChatAppFunctionService#searchMessages" + const val FUNCTION_ID_REVIEW_SEND_MESSAGE = + "com.example.chatapp.appfunctions.ChatAppFunctionService#reviewSendMessage" } } From 03baa118b503ac589fdbe642b25d81403127f009 Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Fri, 20 Nov 2026 17:24:10 +0000 Subject: [PATCH 5/9] cleanup of XML and service --- ChatApp/app/src/main/res/xml/app_metadata.xml | 8 +- .../BaseChatAppFunctionService.kt | 401 +++++++++--------- 2 files changed, 207 insertions(+), 202 deletions(-) diff --git a/ChatApp/app/src/main/res/xml/app_metadata.xml b/ChatApp/app/src/main/res/xml/app_metadata.xml index 57d9673e..3adc62af 100644 --- a/ChatApp/app/src/main/res/xml/app_metadata.xml +++ b/ChatApp/app/src/main/res/xml/app_metadata.xml @@ -17,10 +17,10 @@ diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt index 8c349d00..13701482 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt @@ -35,7 +35,9 @@ import com.example.chatapp.data.RecipientsRepository import com.example.chatapp.data.WallpaperRepository import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext import org.json.JSONArray import org.json.JSONObject import javax.inject.Inject @@ -60,7 +62,6 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { /** * Search for message recipients or chat groups by name or email. - * Required workflow: Call this before "send" or "makeCall" to obtain a valid endpointValue (unique ID). * * @param query Search string for contact name, email, or group name. Throws [AppFunctionInvalidArgumentException] if empty. * @param contactType Filter results by entity type. Accepts "INDIVIDUAL", "GROUP", or "ANY". @@ -72,46 +73,46 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { query: String, @AppFunctionStringValueConstraint(enumValues = ["INDIVIDUAL", "GROUP", "ANY"]) contactType: String, - ): List { - if (query.isBlank()) { - throw AppFunctionInvalidArgumentException("Query cannot be empty") - } - val recipients = - when (contactType) { - "INDIVIDUAL" -> { - recipientsRepository.searchRecipients(query, 3) - } - "GROUP" -> { - recipientsRepository.searchGroups(query, 3).map { - ContactSearchResult( - contactDisplayName = it.name, - contactType = "GROUP", - endpointValue = it.id, - endpointDisplayName = it.name, + ): List = + withContext(Dispatchers.IO) { + if (query.isBlank()) { + throw AppFunctionInvalidArgumentException("Query cannot be empty") + } + val recipients = + when (contactType) { + "INDIVIDUAL" -> { + recipientsRepository.searchRecipients(query, 3) + } + "GROUP" -> { + recipientsRepository.searchGroups(query, 3).map { + ContactSearchResult( + contactDisplayName = it.name, + contactType = "GROUP", + endpointValue = it.id, + endpointDisplayName = it.name, + ) + } + } + "ANY" -> { + recipientsRepository.searchAny(query, maxCount = 3) + } + else -> { + throw AppFunctionInvalidArgumentException( + "Invalid contactType: $contactType. Must be INDIVIDUAL, GROUP, or ANY.", ) } } - "ANY" -> { - recipientsRepository.searchAny(query, maxCount = 3) - } - else -> { - throw AppFunctionInvalidArgumentException( - "Invalid contactType: $contactType. Must be INDIVIDUAL, GROUP, or ANY.", - ) - } - } - if (recipients.isEmpty()) { - throw AppFunctionInvalidArgumentException( - "$contactType with name $query not found. Ask the user to clarify the name", - ) + if (recipients.isEmpty()) { + throw AppFunctionInvalidArgumentException( + "$contactType with name $query not found. Ask the user to clarify the name", + ) + } + recipients } - return recipients - } /** * Fetch details for sending a message before execution. - * Required workflow: Call "searchContacts" first to obtain a valid endpointValue. * * @param endpointValue The unique identifier for the recipient or group obtained from searchContacts. * @param messageBody The text content of the message to send. Cannot be empty or blank. @@ -126,73 +127,73 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { endpointValue: String, messageBody: String, imageUris: List? = null, - ): ConfirmationPreview { - if (messageBody.isBlank()) { - throw AppFunctionInvalidArgumentException("Message body cannot be empty") - } - val displayName = - recipientsRepository.getRecipientById(endpointValue)?.name - ?: recipientsRepository.getGroupById(endpointValue)?.name - ?: throw AppFunctionElementNotFoundException( - "No contact or group found for endpointValue: $endpointValue", - ) - - val surfaceId = "surface_$endpointValue" - val catalogId = - "https://developers.google.com/connected-apps/a2ui/v0_9/comms_catalog_preview.json" - - val createSurface = - JSONObject().apply { - put("version", "v0.9") - put( - "createSurface", - JSONObject().apply { - put("surfaceId", surfaceId) - put("catalogId", catalogId) - }, - ) + ): ConfirmationPreview = + withContext(Dispatchers.IO) { + if (messageBody.isBlank()) { + throw AppFunctionInvalidArgumentException("Message body cannot be empty") } + val displayName = + recipientsRepository.getRecipientById(endpointValue)?.name + ?: recipientsRepository.getGroupById(endpointValue)?.name + ?: throw AppFunctionElementNotFoundException( + "No contact or group found for endpointValue: $endpointValue", + ) - val confirmationComponent = - JSONObject().apply { - put("component", "MessageConfirmationComponent") - put("id", "root") - put("contactDisplayName", displayName) - put("endpointDisplayName", "ChatApp") - put("messageBody", messageBody) - put("editMessageUri", buildEditMessageUri(endpointValue, messageBody)) - } + val surfaceId = "surface_$endpointValue" + val catalogId = + "https://developers.google.com/connected-apps/a2ui/v0_9/comms_catalog_preview.json" + + val createSurface = + JSONObject().apply { + put("version", "v0.9") + put( + "createSurface", + JSONObject().apply { + put("surfaceId", surfaceId) + put("catalogId", catalogId) + }, + ) + } - val updateComponents = - JSONObject().apply { - put("version", "v0.9") - put( - "updateComponents", - JSONObject().apply { - put("surfaceId", surfaceId) - put("components", JSONArray().put(confirmationComponent).toString()) - }, - ) - } + val confirmationComponent = + JSONObject().apply { + put("component", "MessageConfirmationComponent") + put("id", "root") + put("contactDisplayName", displayName) + put("endpointDisplayName", "ChatApp") + put("messageBody", messageBody) + put("editMessageUri", buildEditMessageUri(endpointValue, messageBody)) + } - val a2uiJsonPayload = - JSONArray().apply { - put(createSurface) - put(updateComponents) - }.toString() + val updateComponents = + JSONObject().apply { + put("version", "v0.9") + put( + "updateComponents", + JSONObject().apply { + put("surfaceId", surfaceId) + put("components", JSONArray().put(confirmationComponent).toString()) + }, + ) + } - val a2uiResource = - AppFunctionTextResource( - mimeType = "application/a2ui+json", - content = a2uiJsonPayload, - ) + val a2uiJsonPayload = + JSONArray().apply { + put(createSurface) + put(updateComponents) + }.toString() - return ConfirmationPreview(resources = listOf(a2uiResource)) - } + val a2uiResource = + AppFunctionTextResource( + mimeType = "application/a2ui+json", + content = a2uiJsonPayload, + ) + + ConfirmationPreview(resources = listOf(a2uiResource)) + } /** * Send a text message with optional image attachments to an individual contact or group. - * Required workflow: Call "searchContacts" first to obtain a valid endpointValue. * * @param endpointValue The unique identifier for the recipient or group obtained from searchContacts. * @param messageBody The text content of the message to send. Cannot be empty or blank. @@ -207,85 +208,87 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { endpointValue: String, messageBody: String, imageUris: List? = null, - ): String { - if (messageBody.isBlank()) { - throw AppFunctionInvalidArgumentException("Message body cannot be empty") - } - val displayName = - recipientsRepository.getRecipientById(endpointValue)?.name - ?: recipientsRepository.getGroupById(endpointValue)?.name - ?: throw AppFunctionElementNotFoundException( - "No contact or group found for endpointValue: $endpointValue", + ): String = + withContext(Dispatchers.IO) { + if (messageBody.isBlank()) { + throw AppFunctionInvalidArgumentException("Message body cannot be empty") + } + val displayName = + recipientsRepository.getRecipientById(endpointValue)?.name + ?: recipientsRepository.getGroupById(endpointValue)?.name + ?: throw AppFunctionElementNotFoundException( + "No contact or group found for endpointValue: $endpointValue", + ) + + try { + messageRepository.send( + text = messageBody, + recipientIds = listOf(endpointValue), + imageUris = imageUris?.map { it.toString() }, ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + throw AppFunctionAppUnknownException("Failed to send message: ${e.message}") + } - try { - messageRepository.send( - text = messageBody, - recipientIds = listOf(endpointValue), - imageUris = imageUris?.map { it.toString() }, - ) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - throw AppFunctionAppUnknownException("Failed to send message: ${e.message}") + "Message sent to: $displayName." } - return "Message sent to: $displayName." - } - /** Prepares message for review, returns PendingIntent to open chat with draft. */ @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun reviewSendMessage( endpointValue: String, messageBody: String, - ): PendingIntent { - val recipientId = - recipientsRepository.getRecipientById(endpointValue)?.id - ?: recipientsRepository.getGroupById(endpointValue)?.id - ?: throw AppFunctionElementNotFoundException( - "No contact or group found for endpointValue: $endpointValue", - ) + ): PendingIntent = + withContext(Dispatchers.IO) { + val recipientId = + recipientsRepository.getRecipientById(endpointValue)?.id + ?: recipientsRepository.getGroupById(endpointValue)?.id + ?: throw AppFunctionElementNotFoundException( + "No contact or group found for endpointValue: $endpointValue", + ) - val intent = - Intent().setClassName(this, "com.example.chatapp.MainActivity").apply { - putExtra("nav_route", "chat/$recipientId?draft=${Uri.encode(messageBody)}") - addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) - } + val intent = + Intent().setClassName(this@BaseChatAppFunctionService, "com.example.chatapp.MainActivity").apply { + putExtra("nav_route", "chat/$recipientId?draft=${Uri.encode(messageBody)}") + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) + } - return PendingIntent.getActivity( - this, - 0, - intent, - PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, - ) - } + PendingIntent.getActivity( + this@BaseChatAppFunctionService, + 0, + intent, + PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, + ) + } /** * Initiate a voice call with an individual contact or group. - * Required workflow: Call "searchContacts" first to obtain a valid endpointValue. * * @param endpointValue The unique identifier for the recipient or group obtained from searchContacts. * @return A [PendingIntent] that launches the call activity in the application UI. * @throws AppFunctionElementNotFoundException If no recipient exists for endpointValue. If thrown, call "searchContacts" to find the correct ID. */ @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) - suspend fun makeCall(endpointValue: String): PendingIntent { - val recipient = - recipientsRepository.getRecipientById(endpointValue) - ?: throw AppFunctionElementNotFoundException( - "No recipient exists for endpointValue: $endpointValue", - ) + suspend fun makeCall(endpointValue: String): PendingIntent = + withContext(Dispatchers.IO) { + val recipient = + recipientsRepository.getRecipientById(endpointValue) + ?: throw AppFunctionElementNotFoundException( + "No recipient exists for endpointValue: $endpointValue", + ) - callManager.startCall(recipient.id) + callManager.startCall(recipient.id) - return PendingIntent.getActivity( - this, - 0, - Intent().setClassName(this, "com.example.chatapp.MainActivity") - .apply { putExtra("nav_route", "call/${recipient.id}") }, - PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, - ) - } + PendingIntent.getActivity( + this@BaseChatAppFunctionService, + 0, + Intent().setClassName(this@BaseChatAppFunctionService, "com.example.chatapp.MainActivity") + .apply { putExtra("nav_route", "call/${recipient.id}") }, + PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, + ) + } /** * Updates the wallpaper image for a specific chat conversation. @@ -297,22 +300,23 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { suspend fun updateChatWallpaper( chatId: String, wallpaperUri: Uri, - ): Boolean { - val resolvedId = - recipientsRepository.getRecipientById(chatId)?.id - ?: recipientsRepository.getGroupById(chatId)?.id - ?: recipientsRepository.searchAny(chatId, maxCount = 1).firstOrNull()?.endpointValue - ?: chatId - val inputStream = - try { - contentResolver.openInputStream(wallpaperUri) - } catch (e: Exception) { - throw AppFunctionInvalidArgumentException("Cannot open wallpaper stream: ${e.message}") - } ?: throw AppFunctionInvalidArgumentException("Cannot open wallpaper stream") - return inputStream.use { stream -> - wallpaperRepository.setWallpaper(resolvedId, stream) + ): Boolean = + withContext(Dispatchers.IO) { + val resolvedId = + recipientsRepository.getRecipientById(chatId)?.id + ?: recipientsRepository.getGroupById(chatId)?.id + ?: recipientsRepository.searchAny(chatId, maxCount = 1).firstOrNull()?.endpointValue + ?: chatId + val inputStream = + try { + contentResolver.openInputStream(wallpaperUri) + } catch (e: Exception) { + throw AppFunctionInvalidArgumentException("Cannot open wallpaper stream: ${e.message}") + } ?: throw AppFunctionInvalidArgumentException("Cannot open wallpaper stream") + inputStream.use { stream -> + wallpaperRepository.setWallpaper(resolvedId, stream) + } } - } /** * Search for messages containing a query string, optionally filtered by a specific recipient. @@ -326,45 +330,46 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { suspend fun searchMessages( query: String, endpointValue: String? = null, - ): List { - if (query.isBlank()) { - throw AppFunctionInvalidArgumentException("Query cannot be empty") - } - val targetIds = - if (endpointValue != null) { - listOf(endpointValue) - } else { - val individuals = recipientsRepository.getAllRecipients().map { it.id } - val groups = recipientsRepository.getAllGroups().map { it.id } - individuals + groups + ): List = + withContext(Dispatchers.IO) { + if (query.isBlank()) { + throw AppFunctionInvalidArgumentException("Query cannot be empty") } + val targetIds = + if (endpointValue != null) { + listOf(endpointValue) + } else { + val individuals = recipientsRepository.getAllRecipients().map { it.id } + val groups = recipientsRepository.getAllGroups().map { it.id } + individuals + groups + } - val results = mutableListOf() - - for (id in targetIds) { - val messages = messageRepository.getMessages(id).first() - val matchingMessages = - messages.filter { it.content.contains(query, ignoreCase = true) } - if (matchingMessages.isNotEmpty()) { - results.add( - MessagesSearchResult( - endpointValue = id, - messages = - matchingMessages.map { - val senderDisplayName = getSenderDisplayName(it, id) - Message( - messageBody = it.content, - timestamp = it.sentAt, - senderDisplayName = senderDisplayName, - ) - }, - ), - ) + val results = mutableListOf() + + for (id in targetIds) { + val messages = messageRepository.getMessages(id).first() + val matchingMessages = + messages.filter { it.content.contains(query, ignoreCase = true) } + if (matchingMessages.isNotEmpty()) { + results.add( + MessagesSearchResult( + endpointValue = id, + messages = + matchingMessages.map { + val senderDisplayName = getSenderDisplayName(it, id) + Message( + messageBody = it.content, + timestamp = it.sentAt, + senderDisplayName = senderDisplayName, + ) + }, + ), + ) + } } - } - return results - } + results + } private fun buildEditMessageUri( endpointValue: String, From 4e30f0d785c827239d426e8c53b22d1884cb3564 Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Fri, 20 Nov 2026 18:16:57 +0000 Subject: [PATCH 6/9] updated dynamic function utilizing AppFunctionSignature and correct scope --- .../chatapp/AppFunctionsViewModelTest.kt | 8 -- .../AppFunctionInstrumentationTest.kt | 75 ------------------- ChatApp/app/src/main/AndroidManifest.xml | 3 + .../com/example/chatapp/MainActivity.kt | 33 ++++++++ .../AppendDraftMessageSignature.kt | 31 ++++++++ .../BaseChatAppFunctionService.kt | 40 ++-------- ChatApp/wear/src/main/AndroidManifest.xml | 3 + 7 files changed, 76 insertions(+), 117 deletions(-) create mode 100644 ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt index 18e3896e..aef9a24e 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt @@ -136,12 +136,4 @@ class AppFunctionsViewModelTest { assertNotNull(result) } - @Test - @SdkSuppress(minSdkVersion = 36) - fun registerReviewSendMessage_enablesFunction() = - runTest { - viewModel.registerReviewSendMessage() - val state = viewModel.uiState.value - assertNotNull(state) - } } diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt index b2de13a9..af60b54d 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt @@ -470,79 +470,4 @@ class AppFunctionInstrumentationTest { assertThat(successResponse).isNotNull() } - @Test - fun testReviewSendMessage_disabledByDefault() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE } - val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - val functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled ?: false).isFalse() - } - - @Test - fun testReviewSendMessage_registrationLifecycle() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE } - - // 1. Enable / Register capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - var functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isTrue() - - // 2. Disable / Unregister capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, - AppFunctionManager.APP_FUNCTION_STATE_DISABLED, - ) - states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isFalse() - } - - @Test - fun testReviewSendMessage_returnsImmutablePendingIntent() = - runBlocking { - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE } - - val testRecipient = recipientsRepository.getAllRecipients().first() - val request = - ExecuteAppFunctionRequest( - targetPackageName = context.packageName, - ChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, - AppFunctionData.Builder( - metadata.parameters, - metadata.components, - ) - .setString("endpointValue", testRecipient.id) - .setString("messageBody", "Draft message for review") - .build(), - ) - - val response = appFunctionManager.executeAppFunction(request) - val successResponse = assertIs(response) - assertThat(successResponse).isNotNull() - } } diff --git a/ChatApp/app/src/main/AndroidManifest.xml b/ChatApp/app/src/main/AndroidManifest.xml index 5b174321..fde41b46 100644 --- a/ChatApp/app/src/main/AndroidManifest.xml +++ b/ChatApp/app/src/main/AndroidManifest.xml @@ -68,6 +68,9 @@ + diff --git a/ChatApp/app/src/main/kotlin/com/example/chatapp/MainActivity.kt b/ChatApp/app/src/main/kotlin/com/example/chatapp/MainActivity.kt index 51278728..3dd042d6 100644 --- a/ChatApp/app/src/main/kotlin/com/example/chatapp/MainActivity.kt +++ b/ChatApp/app/src/main/kotlin/com/example/chatapp/MainActivity.kt @@ -15,10 +15,12 @@ */ package com.example.chatapp +import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge +import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.tooling.preview.Preview @@ -33,13 +35,28 @@ import com.example.chatapp.uicomponents.AppFunctionsScreen import com.example.chatapp.uicomponents.CallScreen import com.example.chatapp.uicomponents.ChatScreen import com.example.chatapp.uicomponents.RecipientsScreen +import androidx.appfunctions.AppFunctionManager +import androidx.appfunctions.ExperimentalAppFunctionsApi +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import com.example.chatapp.appfunctions.AppendDraftMessageSignature import dagger.hilt.android.AndroidEntryPoint +import kotlinx.coroutines.launch +@OptIn(ExperimentalAppFunctionsApi::class) @AndroidEntryPoint class MainActivity : ComponentActivity() { + private val appFunctionManager by lazy { AppFunctionManager.getInstance(this) } + private val appendDraftAdapter by lazy { + appFunctionManager?.getHandleAppFunctionRequestAdapter() + } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() + if (Build.VERSION.SDK_INT >= 37) { + setupActivityScopedAppFunctions() + } setContent { ChatAppTheme { val navController = rememberNavController() @@ -117,6 +134,22 @@ class MainActivity : ComponentActivity() { } } } + + @RequiresApi(37) + private fun setupActivityScopedAppFunctions() { + val manager = appFunctionManager ?: return + val adapter = appendDraftAdapter ?: return + + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.RESUMED) { + manager.handleAppFunction( + adapter.adapt { _ -> + true + }, + ) + } + } + } } @Preview(showBackground = true) diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt new file mode 100644 index 00000000..180f662d --- /dev/null +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt @@ -0,0 +1,31 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.chatapp.appfunctions + +import androidx.appfunctions.AppFunctionSignature +import androidx.appfunctions.ExperimentalAppFunctionsApi +import androidx.appfunctions.metadata.AppFunctionMetadata + +@OptIn(ExperimentalAppFunctionsApi::class) +@AppFunctionSignature( + scope = AppFunctionMetadata.SCOPE_ACTIVITY, + appFunctionXmlFileName = "chat_activity_app_functions", + isDescribedByKDoc = true, +) +fun interface AppendDraftMessageSignature { + /** Appends or prefills text content into the currently active chat input bar. */ + suspend fun appendDraftMessage(messageText: String): Boolean +} diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt index 13701482..41d1ae58 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt @@ -68,7 +68,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @return List of [ContactSearchResult] objects matching the query. * @throws AppFunctionInvalidArgumentException If query is empty or blank, an invalid contactType is provided, or if no matching contact or group is found. If thrown, suggest the user clarify the recipient or group name. */ - @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + @AppFunctionDeclaration(isDescribedByKDoc = true) suspend fun searchContacts( query: String, @AppFunctionStringValueConstraint(enumValues = ["INDIVIDUAL", "GROUP", "ANY"]) @@ -122,7 +122,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @throws AppFunctionElementNotFoundException If no contact or group matches endpointValue. If thrown, call "searchContacts" to find the correct ID. */ @OptIn(ExperimentalAppFunctionsApi::class) - @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + @AppFunctionDeclaration(isDescribedByKDoc = true) suspend fun fetchSendMessageDetails( endpointValue: String, messageBody: String, @@ -203,7 +203,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @throws AppFunctionElementNotFoundException If no contact or group matches endpointValue. If thrown, call "searchContacts" to find the correct ID. * @throws AppFunctionAppUnknownException If sending fails due to a repository error. If thrown, suggest the user retry later. */ - @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + @AppFunctionDeclaration(isDescribedByKDoc = true) suspend fun sendMessage( endpointValue: String, messageBody: String, @@ -235,34 +235,6 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { "Message sent to: $displayName." } - /** Prepares message for review, returns PendingIntent to open chat with draft. */ - @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) - suspend fun reviewSendMessage( - endpointValue: String, - messageBody: String, - ): PendingIntent = - withContext(Dispatchers.IO) { - val recipientId = - recipientsRepository.getRecipientById(endpointValue)?.id - ?: recipientsRepository.getGroupById(endpointValue)?.id - ?: throw AppFunctionElementNotFoundException( - "No contact or group found for endpointValue: $endpointValue", - ) - - val intent = - Intent().setClassName(this@BaseChatAppFunctionService, "com.example.chatapp.MainActivity").apply { - putExtra("nav_route", "chat/$recipientId?draft=${Uri.encode(messageBody)}") - addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) - } - - PendingIntent.getActivity( - this@BaseChatAppFunctionService, - 0, - intent, - PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, - ) - } - /** * Initiate a voice call with an individual contact or group. * @@ -270,7 +242,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @return A [PendingIntent] that launches the call activity in the application UI. * @throws AppFunctionElementNotFoundException If no recipient exists for endpointValue. If thrown, call "searchContacts" to find the correct ID. */ - @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + @AppFunctionDeclaration(isDescribedByKDoc = true) suspend fun makeCall(endpointValue: String): PendingIntent = withContext(Dispatchers.IO) { val recipient = @@ -296,7 +268,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @param chatId The unique identifier for the recipient or chat group. * @param wallpaperUri The URI of the image file to set as the chat wallpaper. */ - @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + @AppFunctionDeclaration(isDescribedByKDoc = true) suspend fun updateChatWallpaper( chatId: String, wallpaperUri: Uri, @@ -326,7 +298,7 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @return List of [MessagesSearchResult] matching the query. * @throws AppFunctionInvalidArgumentException If the query is blank. */ - @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + @AppFunctionDeclaration(isDescribedByKDoc = true) suspend fun searchMessages( query: String, endpointValue: String? = null, diff --git a/ChatApp/wear/src/main/AndroidManifest.xml b/ChatApp/wear/src/main/AndroidManifest.xml index 43298159..1ffdcd76 100644 --- a/ChatApp/wear/src/main/AndroidManifest.xml +++ b/ChatApp/wear/src/main/AndroidManifest.xml @@ -65,6 +65,9 @@ + From dbc46027f4b06083201131e3418956ad15458b63 Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Fri, 20 Nov 2026 18:28:59 +0000 Subject: [PATCH 7/9] cleanup and removal of prior efforts --- .../chatapp/AppFunctionsViewModelTest.kt | 78 ----- .../AppFunctionInstrumentationTest.kt | 304 ------------------ .../example/chatapp/AppFunctionsViewModel.kt | 175 ---------- 3 files changed, 557 deletions(-) diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt index aef9a24e..9be2bd64 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt @@ -18,7 +18,6 @@ package com.example.chatapp import android.app.Application import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.filters.SdkSuppress import com.example.chatapp.appfunctions.ChatAppFunctionService import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest @@ -59,81 +58,4 @@ class AppFunctionsViewModelTest { val state = viewModel.uiState.first() assertNotNull(state) } - - @Test - @SdkSuppress(minSdkVersion = 36) - fun registerSearchContacts_enablesFunction() = - runTest { - viewModel.registerSearchContacts() - val state = viewModel.uiState.value - assertNotNull(state) - } - - @Test - @SdkSuppress(minSdkVersion = 36) - fun onUserAuthStateChanged_togglesRegistration() = - runTest { - viewModel.onUserAuthStateChanged(isSignedIn = true) - var state = viewModel.uiState.value - assertNotNull(state) - - viewModel.onUserAuthStateChanged(isSignedIn = false) - state = viewModel.uiState.value - assertNotNull(state) - } - - @Test - @SdkSuppress(minSdkVersion = 36) - fun registerFetchSendMessageDetails_enablesFunction() = - runTest { - viewModel.registerFetchSendMessageDetails() - val state = viewModel.uiState.value - assertNotNull(state) - } - - @Test - @SdkSuppress(minSdkVersion = 36) - fun registerSendMessage_enablesFunction() = - runTest { - viewModel.registerSendMessage() - val state = viewModel.uiState.value - assertNotNull(state) - } - - @Test - @SdkSuppress(minSdkVersion = 36) - fun registerMakeCall_enablesFunction() = - runTest { - viewModel.registerMakeCall() - val state = viewModel.uiState.value - assertNotNull(state) - } - - @Test - @SdkSuppress(minSdkVersion = 36) - fun registerUpdateChatWallpaper_enablesFunction() = - runTest { - viewModel.registerUpdateChatWallpaper() - val state = viewModel.uiState.value - assertNotNull(state) - } - - @Test - @SdkSuppress(minSdkVersion = 36) - fun registerSearchMessages_enablesFunction() = - runTest { - viewModel.registerSearchMessages() - val state = viewModel.uiState.value - assertNotNull(state) - } - - @Test - @SdkSuppress(minSdkVersion = 36) - fun invokeFetchSendMessageDetailsInternally_executesSuccessfully() = - runTest { - viewModel.registerFetchSendMessageDetails() - val result = viewModel.invokeFetchSendMessageDetailsInternally("1", "Test Preview") - assertNotNull(result) - } - } diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt index af60b54d..2a0d5219 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt @@ -63,10 +63,6 @@ class AppFunctionInstrumentationTest { @Test fun testSend_success() = runBlocking { - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) val sendMessageFunctionMetadata = appFunctionManager .searchAppFunctions( @@ -103,10 +99,6 @@ class AppFunctionInstrumentationTest { @Test fun testSend_emptyContent_fails() = runBlocking { - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) val sendMessageFunctionMetadata = appFunctionManager .searchAppFunctions( @@ -136,10 +128,6 @@ class AppFunctionInstrumentationTest { @Test fun testSearchContacts_success() = runBlocking { - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) val getRecipientsFunctionMetadata = appFunctionManager .searchAppFunctions( @@ -178,296 +166,4 @@ class AppFunctionInstrumentationTest { ), ) } - - @Test - fun testSearchContacts_disabledByDefault() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS } - val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - val searchContactsState = states.singleOrNull { it.functionName == metadata.name } - assertThat(searchContactsState?.isEnabled ?: false).isFalse() - } - - @Test - fun testSearchContacts_registrationLifecycle() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS } - - // 1. Enable / Register capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - var searchContactsState = states.singleOrNull { it.functionName == metadata.name } - assertThat(searchContactsState?.isEnabled).isTrue() - - // 2. Disable / Unregister capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, - AppFunctionManager.APP_FUNCTION_STATE_DISABLED, - ) - states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - searchContactsState = states.singleOrNull { it.functionName == metadata.name } - assertThat(searchContactsState?.isEnabled).isFalse() - } - - @Test - fun testFetchSendMessageDetails_disabledByDefault() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS } - val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - val functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled ?: false).isFalse() - } - - @Test - fun testFetchSendMessageDetails_registrationLifecycle() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS } - - // 1. Enable / Register capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - var functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isTrue() - - // 2. Disable / Unregister capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, - AppFunctionManager.APP_FUNCTION_STATE_DISABLED, - ) - states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isFalse() - } - - @Test - fun testSendMessage_disabledByDefault() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE } - val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - val functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled ?: false).isFalse() - } - - @Test - fun testSendMessage_registrationLifecycle() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE } - - // 1. Enable / Register capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - var functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isTrue() - - // 2. Disable / Unregister capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, - AppFunctionManager.APP_FUNCTION_STATE_DISABLED, - ) - states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isFalse() - } - - @Test - fun testMakeCall_disabledByDefault() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_MAKE_CALL } - val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - val functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled ?: false).isFalse() - } - - @Test - fun testMakeCall_registrationLifecycle() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_MAKE_CALL } - - // 1. Enable / Register capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_MAKE_CALL, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - var functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isTrue() - - // 2. Disable / Unregister capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_MAKE_CALL, - AppFunctionManager.APP_FUNCTION_STATE_DISABLED, - ) - states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isFalse() - } - - @Test - fun testUpdateChatWallpaper_disabledByDefault() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER } - val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - val functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled ?: false).isFalse() - } - - @Test - fun testUpdateChatWallpaper_registrationLifecycle() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER } - - // 1. Enable / Register capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - var functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isTrue() - - // 2. Disable / Unregister capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, - AppFunctionManager.APP_FUNCTION_STATE_DISABLED, - ) - states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isFalse() - } - - @Test - fun testSearchMessages_disabledByDefault() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES } - val states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - val functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled ?: false).isFalse() - } - - @Test - fun testSearchMessages_registrationLifecycle() = - runBlocking { - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES } - - // 1. Enable / Register capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - var states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - var functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isTrue() - - // 2. Disable / Unregister capability - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, - AppFunctionManager.APP_FUNCTION_STATE_DISABLED, - ) - states = appFunctionManager.getAppFunctionStates(listOf(metadata.name)) - functionState = states.singleOrNull { it.functionName == metadata.name } - assertThat(functionState?.isEnabled).isFalse() - } - - @Test - fun testFetchSendMessageDetails_selfInvocation() = - runBlocking { - appFunctionManager.setAppFunctionEnabled( - ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, - AppFunctionManager.APP_FUNCTION_STATE_ENABLED, - ) - val metadata = - appFunctionManager - .searchAppFunctions( - AppFunctionSearchSpec(packageNames = setOf(context.packageName)), - ) - .single { it.id == ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS } - - val testRecipient = recipientsRepository.getAllRecipients().first() - val request = - ExecuteAppFunctionRequest( - targetPackageName = context.packageName, - ChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, - AppFunctionData.Builder( - metadata.parameters, - metadata.components, - ) - .setString("endpointValue", testRecipient.id) - .setString("messageBody", "Test Preview") - .build(), - ) - - val response = appFunctionManager.executeAppFunction(request) - val successResponse = assertIs(response) - assertThat(successResponse).isNotNull() - } - } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt index f44e11ac..c32de53f 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt @@ -16,15 +16,10 @@ package com.example.chatapp import android.app.Application -import androidx.annotation.RequiresApi -import androidx.appfunctions.AppFunctionData import androidx.appfunctions.AppFunctionManager import androidx.appfunctions.AppFunctionSearchSpec -import androidx.appfunctions.ExecuteAppFunctionRequest -import androidx.appfunctions.ExecuteAppFunctionResponse import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope -import com.example.chatapp.appfunctions.BaseChatAppFunctionService import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted @@ -127,174 +122,4 @@ class AppFunctionsViewModel appFunctionManager?.setAppFunctionEnabled(id, newState) } } - - /** - * Registers (enables) the searchContacts capability with the OS at runtime. - */ - @RequiresApi(36) - fun registerSearchContacts() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, enabled = true) - } - - /** - * Unregisters (disables) the searchContacts capability with the OS at runtime. - */ - @RequiresApi(36) - fun unregisterSearchContacts() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_CONTACTS, enabled = false) - } - - /** - * Registers (enables) the fetchSendMessageDetails capability with the OS at runtime. - */ - @RequiresApi(36) - fun registerFetchSendMessageDetails() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, enabled = true) - } - - /** - * Unregisters (disables) the fetchSendMessageDetails capability with the OS at runtime. - */ - @RequiresApi(36) - fun unregisterFetchSendMessageDetails() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, enabled = false) - } - - /** - * Registers (enables) the sendMessage capability with the OS at runtime. - */ - @RequiresApi(36) - fun registerSendMessage() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, enabled = true) - } - - /** - * Unregisters (disables) the sendMessage capability with the OS at runtime. - */ - @RequiresApi(36) - fun unregisterSendMessage() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, enabled = false) - } - - /** - * Registers (enables) the makeCall capability with the OS at runtime. - */ - @RequiresApi(36) - fun registerMakeCall() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_MAKE_CALL, enabled = true) - } - - /** - * Unregisters (disables) the makeCall capability with the OS at runtime. - */ - @RequiresApi(36) - fun unregisterMakeCall() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_MAKE_CALL, enabled = false) - } - - /** - * Registers (enables) the updateChatWallpaper capability with the OS at runtime. - */ - @RequiresApi(36) - fun registerUpdateChatWallpaper() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, enabled = true) - } - - /** - * Unregisters (disables) the updateChatWallpaper capability with the OS at runtime. - */ - @RequiresApi(36) - fun unregisterUpdateChatWallpaper() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, enabled = false) - } - - /** - * Registers (enables) the searchMessages capability with the OS at runtime. - */ - @RequiresApi(36) - fun registerSearchMessages() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, enabled = true) - } - - /** - * Unregisters (disables) the searchMessages capability with the OS at runtime. - */ - @RequiresApi(36) - fun unregisterSearchMessages() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_SEARCH_MESSAGES, enabled = false) - } - - /** - * Registers (enables) the reviewSendMessage capability with the OS at runtime. - */ - @RequiresApi(36) - fun registerReviewSendMessage() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, enabled = true) - } - - /** - * Unregisters (disables) the reviewSendMessage capability with the OS at runtime. - */ - @RequiresApi(36) - fun unregisterReviewSendMessage() { - toggleFunction(BaseChatAppFunctionService.FUNCTION_ID_REVIEW_SEND_MESSAGE, enabled = false) - } - - /** - * Handles user authentication state changes to dynamically register or unregister - * app capabilities with the OS at runtime. - */ - @RequiresApi(36) - fun onUserAuthStateChanged(isSignedIn: Boolean) { - if (isSignedIn) { - registerSearchContacts() - registerFetchSendMessageDetails() - registerSendMessage() - registerMakeCall() - registerUpdateChatWallpaper() - registerSearchMessages() - registerReviewSendMessage() - } else { - unregisterSearchContacts() - unregisterFetchSendMessageDetails() - unregisterSendMessage() - unregisterMakeCall() - unregisterUpdateChatWallpaper() - unregisterSearchMessages() - unregisterReviewSendMessage() - } - } - - /** - * Invokes the app-private fetchSendMessageDetails AppFunction internally from within ChatApp. - * - * @param endpointValue The recipient or group identifier. - * @param messageBody The text message body. - * @return The execution response from AppFunctionManager. - */ - @RequiresApi(36) - suspend fun invokeFetchSendMessageDetailsInternally( - endpointValue: String, - messageBody: String, - ): ExecuteAppFunctionResponse? { - if (appFunctionManager == null) return null - val packageName = getApplication().packageName - val searchSpec = AppFunctionSearchSpec(packageNames = setOf(packageName)) - val metadata = - appFunctionManager.searchAppFunctions(searchSpec) - .singleOrNull { it.id == BaseChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS } - ?: return null - - val request = - ExecuteAppFunctionRequest( - targetPackageName = packageName, - BaseChatAppFunctionService.FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS, - AppFunctionData.Builder(metadata.parameters, metadata.components) - .setString("endpointValue", endpointValue) - .setString("messageBody", messageBody) - .build(), - ) - - return appFunctionManager.executeAppFunction(request) - } } From 93403ac35e00f76fa816b5e68896217aa59427b5 Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Wed, 25 Nov 2026 20:32:36 +0000 Subject: [PATCH 8/9] dynamic function cleanup and toggle availability, gating enhancements, UI toggle, WIP --- .../chatapp/AppFunctionsViewModelTest.kt | 10 +- .../AppFunctionInstrumentationTest.kt | 80 ++++ .../com/example/chatapp/MainActivity.kt | 33 -- .../uicomponents/AppFunctionsScreen.kt | 87 +++- .../chatapp/uicomponents/ChatScreen.kt | 60 ++- ChatApp/app/src/main/res/xml/app_metadata.xml | 4 +- .../example/chatapp/AppFunctionsViewModel.kt | 39 +- .../com/example/chatapp/ChatViewModel.kt | 13 + .../chatapp/appfunctions/AppFunctionModule.kt | 38 ++ .../AppendDraftMessageSignature.kt | 7 +- .../BaseChatAppFunctionService.kt | 396 +++++++++--------- .../example/chatapp/data/MessageRepository.kt | 114 +++-- .../chatapp/data/WallpaperRepository.kt | 8 +- .../example/chatapp/di/CoroutinesModule.kt | 39 ++ ChatApp/wear/src/main/AndroidManifest.xml | 3 - .../uicomponents/WearAppFunctionsScreen.kt | 87 +++- .../wear/src/main/res/xml/app_metadata.xml | 6 +- 17 files changed, 706 insertions(+), 318 deletions(-) create mode 100644 ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt create mode 100644 ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt index 9be2bd64..d7769c55 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/AppFunctionsViewModelTest.kt @@ -34,7 +34,7 @@ class AppFunctionsViewModelTest { @Before fun setUp() { application = ApplicationProvider.getApplicationContext() - viewModel = AppFunctionsViewModel(application) + viewModel = AppFunctionsViewModel(application, androidx.appfunctions.AppFunctionManager.getInstance(application)) } @Test @@ -58,4 +58,12 @@ class AppFunctionsViewModelTest { val state = viewModel.uiState.first() assertNotNull(state) } + + @Test + fun uiState_categorizesFunctionsCorrectly() = + runTest { + val state = viewModel.uiState.first() + assertNotNull(state.baselineFunctions) + assertNotNull(state.advancedFunctions) + } } diff --git a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt index 2a0d5219..ecc5f8c1 100644 --- a/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt +++ b/ChatApp/app/src/androidTest/kotlin/com/example/chatapp/appfunctions/AppFunctionInstrumentationTest.kt @@ -63,6 +63,10 @@ class AppFunctionInstrumentationTest { @Test fun testSend_success() = runBlocking { + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) val sendMessageFunctionMetadata = appFunctionManager .searchAppFunctions( @@ -99,6 +103,10 @@ class AppFunctionInstrumentationTest { @Test fun testSend_emptyContent_fails() = runBlocking { + appFunctionManager.setAppFunctionEnabled( + ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) val sendMessageFunctionMetadata = appFunctionManager .searchAppFunctions( @@ -166,4 +174,76 @@ class AppFunctionInstrumentationTest { ), ) } + + @Test + fun testHighSensitivityFunctions_disabledByDefault() = + runBlocking { + val highSensitivityIds = + listOf( + ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, + ChatAppFunctionService.FUNCTION_ID_MAKE_CALL, + ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, + ChatAppFunctionService.FUNCTION_ID_DELETE_MESSAGE, + ) + val functions = + appFunctionManager.searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + val functionNames = + functions.filter { it.id in highSensitivityIds }.map { it.name } + if (functionNames.isNotEmpty()) { + val states = appFunctionManager.getAppFunctionStates(functionNames) + for (state in states) { + assertThat(state.isEnabled).isFalse() + } + } + } + + @Test + fun testAdvancedAgentFeatures_enableAndDisableLifecycle() = + runBlocking { + val highSensitivityIds = + listOf( + ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE, + ChatAppFunctionService.FUNCTION_ID_MAKE_CALL, + ChatAppFunctionService.FUNCTION_ID_UPDATE_CHAT_WALLPAPER, + ChatAppFunctionService.FUNCTION_ID_DELETE_MESSAGE, + ) + + // 1. Enable batch + for (id in highSensitivityIds) { + appFunctionManager.setAppFunctionEnabled( + id, + AppFunctionManager.APP_FUNCTION_STATE_ENABLED, + ) + } + + val functions = + appFunctionManager.searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + val functionNames = + functions.filter { it.id in highSensitivityIds }.map { it.name } + if (functionNames.isNotEmpty()) { + var states = appFunctionManager.getAppFunctionStates(functionNames) + for (state in states) { + assertThat(state.isEnabled).isTrue() + } + } + + // 2. Disable batch + for (id in highSensitivityIds) { + appFunctionManager.setAppFunctionEnabled( + id, + AppFunctionManager.APP_FUNCTION_STATE_DISABLED, + ) + } + + if (functionNames.isNotEmpty()) { + val states = appFunctionManager.getAppFunctionStates(functionNames) + for (state in states) { + assertThat(state.isEnabled).isFalse() + } + } + } } diff --git a/ChatApp/app/src/main/kotlin/com/example/chatapp/MainActivity.kt b/ChatApp/app/src/main/kotlin/com/example/chatapp/MainActivity.kt index 3dd042d6..51278728 100644 --- a/ChatApp/app/src/main/kotlin/com/example/chatapp/MainActivity.kt +++ b/ChatApp/app/src/main/kotlin/com/example/chatapp/MainActivity.kt @@ -15,12 +15,10 @@ */ package com.example.chatapp -import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge -import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.tooling.preview.Preview @@ -35,28 +33,13 @@ import com.example.chatapp.uicomponents.AppFunctionsScreen import com.example.chatapp.uicomponents.CallScreen import com.example.chatapp.uicomponents.ChatScreen import com.example.chatapp.uicomponents.RecipientsScreen -import androidx.appfunctions.AppFunctionManager -import androidx.appfunctions.ExperimentalAppFunctionsApi -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.lifecycleScope -import androidx.lifecycle.repeatOnLifecycle -import com.example.chatapp.appfunctions.AppendDraftMessageSignature import dagger.hilt.android.AndroidEntryPoint -import kotlinx.coroutines.launch -@OptIn(ExperimentalAppFunctionsApi::class) @AndroidEntryPoint class MainActivity : ComponentActivity() { - private val appFunctionManager by lazy { AppFunctionManager.getInstance(this) } - private val appendDraftAdapter by lazy { - appFunctionManager?.getHandleAppFunctionRequestAdapter() - } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() - if (Build.VERSION.SDK_INT >= 37) { - setupActivityScopedAppFunctions() - } setContent { ChatAppTheme { val navController = rememberNavController() @@ -134,22 +117,6 @@ class MainActivity : ComponentActivity() { } } } - - @RequiresApi(37) - private fun setupActivityScopedAppFunctions() { - val manager = appFunctionManager ?: return - val adapter = appendDraftAdapter ?: return - - lifecycleScope.launch { - repeatOnLifecycle(Lifecycle.State.RESUMED) { - manager.handleAppFunction( - adapter.adapt { _ -> - true - }, - ) - } - } - } } @Preview(showBackground = true) diff --git a/ChatApp/app/src/main/kotlin/com/example/chatapp/uicomponents/AppFunctionsScreen.kt b/ChatApp/app/src/main/kotlin/com/example/chatapp/uicomponents/AppFunctionsScreen.kt index 02920b53..37e93475 100644 --- a/ChatApp/app/src/main/kotlin/com/example/chatapp/uicomponents/AppFunctionsScreen.kt +++ b/ChatApp/app/src/main/kotlin/com/example/chatapp/uicomponents/AppFunctionsScreen.kt @@ -25,17 +25,26 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Switch import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight @@ -57,6 +66,35 @@ fun AppFunctionsScreen( onBackClick: () -> Unit, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() + var showAdvancedDialog by rememberSaveable { mutableStateOf(false) } + + if (showAdvancedDialog) { + AlertDialog( + onDismissRequest = { showAdvancedDialog = false }, + title = { Text("Advanced AI Agent Features") }, + text = { + if (uiState.advancedFunctions.isEmpty()) { + Text("No advanced functions available.") + } else { + LazyColumn { + items(uiState.advancedFunctions) { function -> + AppFunctionItem( + id = function.id, + isEnabled = function.isEnabled, + description = function.description, + onToggle = { enabled -> viewModel.toggleFunction(function.id, enabled) }, + ) + } + } + } + }, + confirmButton = { + TextButton(onClick = { showAdvancedDialog = false }) { + Text("Close") + } + }, + ) + } Scaffold( topBar = { @@ -97,16 +135,61 @@ fun AppFunctionsScreen( modifier = Modifier.fillMaxSize(), contentPadding = innerPadding, ) { + item { + Card( + onClick = { showAdvancedDialog = true }, + modifier = + Modifier + .fillMaxWidth() + .padding(16.dp), + colors = + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + ), + ) { + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = "Advanced AI Agent Features", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSecondaryContainer, + ) + Text( + text = "Tap to manage high-sensitivity capabilities", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.8f), + ) + } + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = "Open Advanced Features", + tint = MaterialTheme.colorScheme.onSecondaryContainer, + ) + } + } + } + + item { + HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp)) + } + item { Text( - text = "Declared AppFunctions", + text = "Standard Functions", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, modifier = Modifier.padding(16.dp), ) } - items(uiState.functions) { function -> + items(uiState.baselineFunctions) { function -> AppFunctionItem( id = function.id, isEnabled = function.isEnabled, diff --git a/ChatApp/app/src/main/kotlin/com/example/chatapp/uicomponents/ChatScreen.kt b/ChatApp/app/src/main/kotlin/com/example/chatapp/uicomponents/ChatScreen.kt index 3d56be52..0c81de2c 100644 --- a/ChatApp/app/src/main/kotlin/com/example/chatapp/uicomponents/ChatScreen.kt +++ b/ChatApp/app/src/main/kotlin/com/example/chatapp/uicomponents/ChatScreen.kt @@ -15,6 +15,9 @@ */ package com.example.chatapp.uicomponents +import android.os.Build +import androidx.appfunctions.AppFunctionManager +import androidx.appfunctions.ExperimentalAppFunctionsApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -51,30 +54,36 @@ import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults.topAppBarColors import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -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.input.nestedscroll.nestedScroll import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.repeatOnLifecycle import coil.compose.AsyncImage import com.example.chatapp.BotMessageState import com.example.chatapp.ChatViewModel import com.example.chatapp.InputBar import com.example.chatapp.R +import com.example.chatapp.appfunctions.AppendDraftMessageSignature import com.example.chatapp.data.DisplayMessage import com.example.chatapp.util.linkifyString +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch -@OptIn(ExperimentalMaterial3Api::class) +@OptIn(ExperimentalMaterial3Api::class, ExperimentalAppFunctionsApi::class) @Composable fun ChatScreen( recipientId: String, @@ -92,7 +101,40 @@ fun ChatScreen( val topAppBarState = rememberTopAppBarState() val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(topAppBarState) val uiState by viewModel.uiState.collectAsStateWithLifecycle() - var message by rememberSaveable { mutableStateOf(initialDraft.orEmpty()) } + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + + DisposableEffect(lifecycleOwner, viewModel) { + if (Build.VERSION.SDK_INT >= 37) { + val appFunctionManager = AppFunctionManager.getInstance(context) + val adapter = + appFunctionManager?.getHandleAppFunctionRequestAdapter() + if (appFunctionManager != null && adapter != null) { + val job = + CoroutineScope(Dispatchers.Main).launch { + lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) { + appFunctionManager.handleAppFunction( + adapter.adapt { text -> + viewModel.appendDraft(text) + true + }, + ) + } + } + onDispose { job.cancel() } + } else { + onDispose {} + } + } else { + onDispose {} + } + } + + androidx.compose.runtime.LaunchedEffect(initialDraft) { + if (!initialDraft.isNullOrEmpty() && uiState.draftText.isEmpty()) { + viewModel.updateDraft(initialDraft) + } + } Box(modifier = Modifier.fillMaxSize()) { uiState.wallpaperPath?.let { path -> @@ -151,14 +193,14 @@ fun ChatScreen( }, bottomBar = { InputBar( - value = message, + value = uiState.draftText, placeholder = stringResource(R.string.input_placeholder), onInputChanged = { - message = it + viewModel.updateDraft(it) }, onSendClick = { uris -> - viewModel.sendMessage(message, uris) - message = "" + viewModel.sendMessage(uiState.draftText, uris) + viewModel.updateDraft("") }, sendEnabled = uiState.botMessageState !is BotMessageState.Generating, modifier = diff --git a/ChatApp/app/src/main/res/xml/app_metadata.xml b/ChatApp/app/src/main/res/xml/app_metadata.xml index 3adc62af..90f0742f 100644 --- a/ChatApp/app/src/main/res/xml/app_metadata.xml +++ b/ChatApp/app/src/main/res/xml/app_metadata.xml @@ -17,10 +17,10 @@ diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt index c32de53f..4cb17cdf 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt @@ -46,10 +46,14 @@ data class AppFunctionInfo( /** * UI state for the App Functions settings screen. * - * @property functions The list of available app functions and their current status. + * @property functions All available app functions. + * @property baselineFunctions Low-risk baseline app functions. + * @property advancedFunctions High-sensitivity advanced app functions. */ data class AppFunctionsUiState( val functions: List = emptyList(), + val baselineFunctions: List = emptyList(), + val advancedFunctions: List = emptyList(), ) /** @@ -63,8 +67,8 @@ class AppFunctionsViewModel @Inject constructor( application: Application, + private val appFunctionManager: AppFunctionManager?, ) : AndroidViewModel(application) { - private val appFunctionManager = AppFunctionManager.getInstance(application) val uiState: StateFlow = appFunctionManager @@ -99,7 +103,17 @@ class AppFunctionsViewModel ) }.sortedBy { it.id } - return AppFunctionsUiState(functions = functionInfos) + val (advanced, baseline) = + functionInfos.partition { info -> + val shortName = info.id.substringAfterLast("#").substringAfterLast(".") + shortName in HIGH_SENSITIVITY_KEYWORDS + } + + return AppFunctionsUiState( + functions = functionInfos, + baselineFunctions = baseline, + advancedFunctions = advanced, + ) } /** @@ -119,7 +133,24 @@ class AppFunctionsViewModel } else { AppFunctionManager.APP_FUNCTION_STATE_DISABLED } - appFunctionManager?.setAppFunctionEnabled(id, newState) + val packageName = getApplication().packageName + val functions = + appFunctionManager?.searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(packageName)), + ).orEmpty() + val targetName = functions.find { it.id == id }?.name ?: id + appFunctionManager?.setAppFunctionEnabled(targetName.toString(), newState) } } + + companion object { + /** High-sensitivity keywords guarded by "Advanced AI Agent Features". */ + val HIGH_SENSITIVITY_KEYWORDS = + setOf( + "sendMessage", + "makeCall", + "updateChatWallpaper", + "deleteMessage", + ) + } } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/ChatViewModel.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/ChatViewModel.kt index 7524d6f7..a79a2229 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/ChatViewModel.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/ChatViewModel.kt @@ -67,6 +67,8 @@ data class ChatbotUiState( val botMessageState: BotMessageState = BotMessageState.WaitingForMessage, /** Optional path to a custom wallpaper image for this chat. */ val wallpaperPath: String? = null, + /** The active draft message text in the input bar. */ + val draftText: String = "", ) @HiltViewModel(assistedFactory = ChatViewModel.Factory::class) @@ -113,6 +115,17 @@ class ChatViewModel } } + fun updateDraft(text: String) { + _uiState.update { it.copy(draftText = text) } + } + + fun appendDraft(text: String) { + _uiState.update { current -> + val newDraft = if (current.draftText.isBlank()) text else "${current.draftText} $text" + current.copy(draftText = newDraft) + } + } + fun startCall() { callManager.startCall(recipientId) } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt new file mode 100644 index 00000000..eb8f26ce --- /dev/null +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt @@ -0,0 +1,38 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.chatapp.appfunctions + +import android.content.Context +import androidx.appfunctions.AppFunctionManager +import dagger.Module +import dagger.Provides +import dagger.hilt.InstallIn +import dagger.hilt.android.qualifiers.ApplicationContext +import dagger.hilt.components.SingletonComponent +import javax.inject.Singleton + +@Module +@InstallIn(SingletonComponent::class) +object AppFunctionModule { + + @Provides + @Singleton + fun provideAppFunctionManager( + @ApplicationContext context: Context, + ): AppFunctionManager? { + return AppFunctionManager.getInstance(context) + } +} diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt index 180f662d..44fbcdbd 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt @@ -26,6 +26,11 @@ import androidx.appfunctions.metadata.AppFunctionMetadata isDescribedByKDoc = true, ) fun interface AppendDraftMessageSignature { - /** Appends or prefills text content into the currently active chat input bar. */ + /** + * Appends or prefills text content into the currently active chat input bar. + * + * @param messageText The text content to prefill or append into the active chat input bar. If text is already present, messageText is appended with a space; otherwise it sets the draft. Cannot be blank. + * @return True if the message text was successfully appended to the active chat input bar, false otherwise. + */ suspend fun appendDraftMessage(messageText: String): Boolean } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt index 41d1ae58..43f1bb14 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/BaseChatAppFunctionService.kt @@ -35,9 +35,7 @@ import com.example.chatapp.data.RecipientsRepository import com.example.chatapp.data.WallpaperRepository import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first -import kotlinx.coroutines.withContext import org.json.JSONArray import org.json.JSONObject import javax.inject.Inject @@ -73,43 +71,42 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { query: String, @AppFunctionStringValueConstraint(enumValues = ["INDIVIDUAL", "GROUP", "ANY"]) contactType: String, - ): List = - withContext(Dispatchers.IO) { - if (query.isBlank()) { - throw AppFunctionInvalidArgumentException("Query cannot be empty") - } - val recipients = - when (contactType) { - "INDIVIDUAL" -> { - recipientsRepository.searchRecipients(query, 3) - } - "GROUP" -> { - recipientsRepository.searchGroups(query, 3).map { - ContactSearchResult( - contactDisplayName = it.name, - contactType = "GROUP", - endpointValue = it.id, - endpointDisplayName = it.name, - ) - } - } - "ANY" -> { - recipientsRepository.searchAny(query, maxCount = 3) - } - else -> { - throw AppFunctionInvalidArgumentException( - "Invalid contactType: $contactType. Must be INDIVIDUAL, GROUP, or ANY.", + ): List { + if (query.isBlank()) { + throw AppFunctionInvalidArgumentException("Query cannot be empty") + } + val recipients = + when (contactType) { + "INDIVIDUAL" -> { + recipientsRepository.searchRecipients(query, 3) + } + "GROUP" -> { + recipientsRepository.searchGroups(query, 3).map { + ContactSearchResult( + contactDisplayName = it.name, + contactType = "GROUP", + endpointValue = it.id, + endpointDisplayName = it.name, ) } } - - if (recipients.isEmpty()) { - throw AppFunctionInvalidArgumentException( - "$contactType with name $query not found. Ask the user to clarify the name", - ) + "ANY" -> { + recipientsRepository.searchAny(query, maxCount = 3) + } + else -> { + throw AppFunctionInvalidArgumentException( + "Invalid contactType: $contactType. Must be INDIVIDUAL, GROUP, or ANY.", + ) + } } - recipients + + if (recipients.isEmpty()) { + throw AppFunctionInvalidArgumentException( + "$contactType with name $query not found. Ask the user to clarify the name", + ) } + return recipients + } /** * Fetch details for sending a message before execution. @@ -127,70 +124,69 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { endpointValue: String, messageBody: String, imageUris: List? = null, - ): ConfirmationPreview = - withContext(Dispatchers.IO) { - if (messageBody.isBlank()) { - throw AppFunctionInvalidArgumentException("Message body cannot be empty") - } - val displayName = - recipientsRepository.getRecipientById(endpointValue)?.name - ?: recipientsRepository.getGroupById(endpointValue)?.name - ?: throw AppFunctionElementNotFoundException( - "No contact or group found for endpointValue: $endpointValue", - ) + ): ConfirmationPreview { + if (messageBody.isBlank()) { + throw AppFunctionInvalidArgumentException("Message body cannot be empty") + } + val displayName = + recipientsRepository.getRecipientById(endpointValue)?.name + ?: recipientsRepository.getGroupById(endpointValue)?.name + ?: throw AppFunctionElementNotFoundException( + "No contact or group found for endpointValue: $endpointValue", + ) - val surfaceId = "surface_$endpointValue" - val catalogId = - "https://developers.google.com/connected-apps/a2ui/v0_9/comms_catalog_preview.json" + val surfaceId = "surface_$endpointValue" + val catalogId = + "https://developers.google.com/connected-apps/a2ui/v0_9/comms_catalog_preview.json" - val createSurface = - JSONObject().apply { - put("version", "v0.9") - put( - "createSurface", - JSONObject().apply { - put("surfaceId", surfaceId) - put("catalogId", catalogId) - }, - ) - } + val createSurface = + JSONObject().apply { + put("version", "v0.9") + put( + "createSurface", + JSONObject().apply { + put("surfaceId", surfaceId) + put("catalogId", catalogId) + }, + ) + } - val confirmationComponent = - JSONObject().apply { - put("component", "MessageConfirmationComponent") - put("id", "root") - put("contactDisplayName", displayName) - put("endpointDisplayName", "ChatApp") - put("messageBody", messageBody) - put("editMessageUri", buildEditMessageUri(endpointValue, messageBody)) - } + val confirmationComponent = + JSONObject().apply { + put("component", "MessageConfirmationComponent") + put("id", "root") + put("contactDisplayName", displayName) + put("endpointDisplayName", "ChatApp") + put("messageBody", messageBody) + put("editMessageUri", buildEditMessageUri(endpointValue, messageBody)) + } - val updateComponents = - JSONObject().apply { - put("version", "v0.9") - put( - "updateComponents", - JSONObject().apply { - put("surfaceId", surfaceId) - put("components", JSONArray().put(confirmationComponent).toString()) - }, - ) - } + val updateComponents = + JSONObject().apply { + put("version", "v0.9") + put( + "updateComponents", + JSONObject().apply { + put("surfaceId", surfaceId) + put("components", JSONArray().put(confirmationComponent).toString()) + }, + ) + } - val a2uiJsonPayload = - JSONArray().apply { - put(createSurface) - put(updateComponents) - }.toString() + val a2uiJsonPayload = + JSONArray().apply { + put(createSurface) + put(updateComponents) + }.toString() - val a2uiResource = - AppFunctionTextResource( - mimeType = "application/a2ui+json", - content = a2uiJsonPayload, - ) + val a2uiResource = + AppFunctionTextResource( + mimeType = "application/a2ui+json", + content = a2uiJsonPayload, + ) - ConfirmationPreview(resources = listOf(a2uiResource)) - } + return ConfirmationPreview(resources = listOf(a2uiResource)) + } /** * Send a text message with optional image attachments to an individual contact or group. @@ -203,38 +199,37 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @throws AppFunctionElementNotFoundException If no contact or group matches endpointValue. If thrown, call "searchContacts" to find the correct ID. * @throws AppFunctionAppUnknownException If sending fails due to a repository error. If thrown, suggest the user retry later. */ - @AppFunctionDeclaration(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun sendMessage( endpointValue: String, messageBody: String, imageUris: List? = null, - ): String = - withContext(Dispatchers.IO) { - if (messageBody.isBlank()) { - throw AppFunctionInvalidArgumentException("Message body cannot be empty") - } - val displayName = - recipientsRepository.getRecipientById(endpointValue)?.name - ?: recipientsRepository.getGroupById(endpointValue)?.name - ?: throw AppFunctionElementNotFoundException( - "No contact or group found for endpointValue: $endpointValue", - ) - - try { - messageRepository.send( - text = messageBody, - recipientIds = listOf(endpointValue), - imageUris = imageUris?.map { it.toString() }, + ): String { + if (messageBody.isBlank()) { + throw AppFunctionInvalidArgumentException("Message body cannot be empty") + } + val displayName = + recipientsRepository.getRecipientById(endpointValue)?.name + ?: recipientsRepository.getGroupById(endpointValue)?.name + ?: throw AppFunctionElementNotFoundException( + "No contact or group found for endpointValue: $endpointValue", ) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - throw AppFunctionAppUnknownException("Failed to send message: ${e.message}") - } - "Message sent to: $displayName." + try { + messageRepository.send( + text = messageBody, + recipientIds = listOf(endpointValue), + imageUris = imageUris?.map { it.toString() }, + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + throw AppFunctionAppUnknownException("Failed to send message: ${e.message}") } + return "Message sent to: $displayName." + } + /** * Initiate a voice call with an individual contact or group. * @@ -242,25 +237,24 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @return A [PendingIntent] that launches the call activity in the application UI. * @throws AppFunctionElementNotFoundException If no recipient exists for endpointValue. If thrown, call "searchContacts" to find the correct ID. */ - @AppFunctionDeclaration(isDescribedByKDoc = true) - suspend fun makeCall(endpointValue: String): PendingIntent = - withContext(Dispatchers.IO) { - val recipient = - recipientsRepository.getRecipientById(endpointValue) - ?: throw AppFunctionElementNotFoundException( - "No recipient exists for endpointValue: $endpointValue", - ) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + suspend fun makeCall(endpointValue: String): PendingIntent { + val recipient = + recipientsRepository.getRecipientById(endpointValue) + ?: throw AppFunctionElementNotFoundException( + "No recipient exists for endpointValue: $endpointValue", + ) - callManager.startCall(recipient.id) + callManager.startCall(recipient.id) - PendingIntent.getActivity( - this@BaseChatAppFunctionService, - 0, - Intent().setClassName(this@BaseChatAppFunctionService, "com.example.chatapp.MainActivity") - .apply { putExtra("nav_route", "call/${recipient.id}") }, - PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, - ) - } + return PendingIntent.getActivity( + this@BaseChatAppFunctionService, + 0, + Intent().setClassName(this@BaseChatAppFunctionService, "com.example.chatapp.MainActivity") + .apply { putExtra("nav_route", "call/${recipient.id}") }, + PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, + ) + } /** * Updates the wallpaper image for a specific chat conversation. @@ -268,27 +262,45 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { * @param chatId The unique identifier for the recipient or chat group. * @param wallpaperUri The URI of the image file to set as the chat wallpaper. */ - @AppFunctionDeclaration(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun updateChatWallpaper( chatId: String, wallpaperUri: Uri, - ): Boolean = - withContext(Dispatchers.IO) { - val resolvedId = - recipientsRepository.getRecipientById(chatId)?.id - ?: recipientsRepository.getGroupById(chatId)?.id - ?: recipientsRepository.searchAny(chatId, maxCount = 1).firstOrNull()?.endpointValue - ?: chatId - val inputStream = - try { - contentResolver.openInputStream(wallpaperUri) - } catch (e: Exception) { - throw AppFunctionInvalidArgumentException("Cannot open wallpaper stream: ${e.message}") - } ?: throw AppFunctionInvalidArgumentException("Cannot open wallpaper stream") - inputStream.use { stream -> - wallpaperRepository.setWallpaper(resolvedId, stream) - } + ): Boolean { + val resolvedId = + recipientsRepository.getRecipientById(chatId)?.id + ?: recipientsRepository.getGroupById(chatId)?.id + ?: recipientsRepository.searchAny(chatId, maxCount = 1).firstOrNull()?.endpointValue + ?: chatId + val inputStream = + try { + contentResolver.openInputStream(wallpaperUri) + } catch (e: Exception) { + throw AppFunctionInvalidArgumentException("Cannot open wallpaper stream: ${e.message}") + } ?: throw AppFunctionInvalidArgumentException("Cannot open wallpaper stream") + return inputStream.use { stream -> + wallpaperRepository.setWallpaper(resolvedId, stream) + } + } + + /** + * Deletes chat messages matching a text query, optionally for a specific contact or group. + * + * @param query The text string to search for and delete. Cannot be empty. + * @param endpointValue Optional unique identifier of the contact or group to restrict deletion to. + * @return True if matching messages were deleted, false if no matching messages were found. + * @throws AppFunctionInvalidArgumentException If the query is blank. + */ + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) + suspend fun deleteMessage( + query: String, + endpointValue: String? = null, + ): Boolean { + if (query.isBlank()) { + throw AppFunctionInvalidArgumentException("Query cannot be empty") } + return messageRepository.deleteMessage(query, endpointValue) + } /** * Search for messages containing a query string, optionally filtered by a specific recipient. @@ -302,47 +314,46 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { suspend fun searchMessages( query: String, endpointValue: String? = null, - ): List = - withContext(Dispatchers.IO) { - if (query.isBlank()) { - throw AppFunctionInvalidArgumentException("Query cannot be empty") + ): List { + if (query.isBlank()) { + throw AppFunctionInvalidArgumentException("Query cannot be empty") + } + val targetIds = + if (endpointValue != null) { + listOf(endpointValue) + } else { + val individuals = recipientsRepository.getAllRecipients().map { it.id } + val groups = recipientsRepository.getAllGroups().map { it.id } + individuals + groups } - val targetIds = - if (endpointValue != null) { - listOf(endpointValue) - } else { - val individuals = recipientsRepository.getAllRecipients().map { it.id } - val groups = recipientsRepository.getAllGroups().map { it.id } - individuals + groups - } - val results = mutableListOf() + val results = mutableListOf() - for (id in targetIds) { - val messages = messageRepository.getMessages(id).first() - val matchingMessages = - messages.filter { it.content.contains(query, ignoreCase = true) } - if (matchingMessages.isNotEmpty()) { - results.add( - MessagesSearchResult( - endpointValue = id, - messages = - matchingMessages.map { - val senderDisplayName = getSenderDisplayName(it, id) - Message( - messageBody = it.content, - timestamp = it.sentAt, - senderDisplayName = senderDisplayName, - ) - }, - ), - ) - } + for (id in targetIds) { + val messages = messageRepository.getMessages(id).first() + val matchingMessages = + messages.filter { it.content.contains(query, ignoreCase = true) } + if (matchingMessages.isNotEmpty()) { + results.add( + MessagesSearchResult( + endpointValue = id, + messages = + matchingMessages.map { + val senderDisplayName = getSenderDisplayName(it, id) + Message( + messageBody = it.content, + timestamp = it.sentAt, + senderDisplayName = senderDisplayName, + ) + }, + ), + ) } - - results } + return results + } + private fun buildEditMessageUri( endpointValue: String, messageBody: String, @@ -369,21 +380,4 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { "Me" } } - - companion object { - const val FUNCTION_ID_SEARCH_CONTACTS = - "com.example.chatapp.appfunctions.ChatAppFunctionService#searchContacts" - const val FUNCTION_ID_FETCH_SEND_MESSAGE_DETAILS = - "com.example.chatapp.appfunctions.ChatAppFunctionService#fetchSendMessageDetails" - const val FUNCTION_ID_SEND_MESSAGE = - "com.example.chatapp.appfunctions.ChatAppFunctionService#sendMessage" - const val FUNCTION_ID_MAKE_CALL = - "com.example.chatapp.appfunctions.ChatAppFunctionService#makeCall" - const val FUNCTION_ID_UPDATE_CHAT_WALLPAPER = - "com.example.chatapp.appfunctions.ChatAppFunctionService#updateChatWallpaper" - const val FUNCTION_ID_SEARCH_MESSAGES = - "com.example.chatapp.appfunctions.ChatAppFunctionService#searchMessages" - const val FUNCTION_ID_REVIEW_SEND_MESSAGE = - "com.example.chatapp.appfunctions.ChatAppFunctionService#reviewSendMessage" - } } diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/data/MessageRepository.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/data/MessageRepository.kt index 5c42fe5a..b767adc4 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/data/MessageRepository.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/data/MessageRepository.kt @@ -16,15 +16,18 @@ package com.example.chatapp.data import android.net.Uri +import com.example.chatapp.di.IoDispatcher import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent +import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update +import kotlinx.coroutines.withContext import java.util.UUID import javax.inject.Inject import javax.inject.Singleton @@ -69,12 +72,26 @@ interface MessageRepository { * @return The response text generated by the bot. */ suspend fun sendToBot(text: String): String + + /** + * Deletes a message matching a query string. + * + * @param query Text content to match for deletion. + * @param recipientId Optional recipient ID filter. + * @return True if a message was deleted. + */ + suspend fun deleteMessage( + query: String, + recipientId: String? = null, + ): Boolean } @Singleton class MessageRepositoryImpl @Inject - constructor() : MessageRepository { + constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + ) : MessageRepository { // Used for message delays. private val random = Random(System.currentTimeMillis()) @@ -106,44 +123,67 @@ class MessageRepositoryImpl text: String, recipientIds: List, imageUris: List?, - ): String { - // Simulate network delay - randomDelay() - val sentAt = System.currentTimeMillis() - - recipientIds.forEach { id -> - saveMessage( - id, - DisplayMessage( - content = text, - sentAt = sentAt, - isInbound = false, - senderName = "Me", - images = imageUris?.map { Uri.parse(it) } ?: emptyList(), - ), - ) + ): String = + withContext(ioDispatcher) { + randomDelay() + val sentAt = System.currentTimeMillis() + + recipientIds.forEach { id -> + saveMessage( + id, + DisplayMessage( + content = text, + sentAt = sentAt, + isInbound = false, + senderName = "Me", + images = imageUris?.map { Uri.parse(it) } ?: emptyList(), + ), + ) + } + UUID.randomUUID().toString() } - return UUID.randomUUID().toString() - } - override suspend fun sendToBot(text: String): String { - // Simulate network delay - randomDelay() - val responses = - listOf( - "Hi there! What's on your mind today?", - "I'd love to hear more about your perspective on this.", - "I don't have personal experiences, but I'm ready to listen!", - "Could you give me an example of what you mean?", - "Makes perfect sense!", - "Welcome! What are we working on right now?", - "That sounds like a fascinating topic to explore.", - "I'm here whenever you're ready to start.", - "Could you break that down a bit further for me?", - "Got it. Let's dive in!", - ) - return responses[Random.nextInt(responses.size)] - } + override suspend fun sendToBot(text: String): String = + withContext(ioDispatcher) { + randomDelay() + val responses = + listOf( + "Hi there! What's on your mind today?", + "I'd love to hear more about your perspective on this.", + "I don't have personal experiences, but I'm ready to listen!", + "Could you give me an example of what you mean?", + "Makes perfect sense!", + "Welcome! What are we working on right now?", + "That sounds like a fascinating topic to explore.", + "I'm here whenever you're ready to start.", + "Could you break that down a bit further for me?", + "Got it. Let's dive in!", + ) + responses[Random.nextInt(responses.size)] + } + + override suspend fun deleteMessage( + query: String, + recipientId: String?, + ): Boolean = + withContext(ioDispatcher) { + randomDelay() + var deletedAny = false + inMemoryMessages.update { currentMap -> + val targetKeys = if (recipientId != null) listOf(recipientId) else currentMap.keys + val newMap = currentMap.toMutableMap() + for (key in targetKeys) { + val list = newMap[key] ?: continue + val filtered = list.filterNot { it.content.contains(query, ignoreCase = true) } + if (filtered.size != list.size) { + deletedAny = true + newMap[key] = filtered + } + } + newMap + } + deletedAny + } } @Module diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/data/WallpaperRepository.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/data/WallpaperRepository.kt index 986e3430..b5a23fdd 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/data/WallpaperRepository.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/data/WallpaperRepository.kt @@ -16,12 +16,13 @@ package com.example.chatapp.data import android.content.Context +import com.example.chatapp.di.IoDispatcher import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent -import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOn @@ -63,6 +64,7 @@ class WallpaperRepositoryImpl @Inject constructor( @ApplicationContext private val context: Context, + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, ) : WallpaperRepository { private val wallpapers = MutableStateFlow>(emptyMap()) @@ -74,14 +76,14 @@ class WallpaperRepositoryImpl ?.maxByOrNull { it.lastModified() } ?.absolutePath } - }.flowOn(Dispatchers.IO) + }.flowOn(ioDispatcher) } override suspend fun setWallpaper( chatId: String, inputStream: InputStream, ): Boolean = - withContext(Dispatchers.IO) { + withContext(ioDispatcher) { try { val dir = File(context.filesDir, "wallpapers").apply { mkdirs() } val newFile = File(dir, "wallpaper_${chatId}_${System.currentTimeMillis()}.jpg") diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt new file mode 100644 index 00000000..8caf629b --- /dev/null +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt @@ -0,0 +1,39 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.chatapp.di + +import dagger.Module +import dagger.Provides +import dagger.hilt.InstallIn +import dagger.hilt.components.SingletonComponent +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import javax.inject.Qualifier +import javax.inject.Singleton + +@Qualifier +@Retention(AnnotationRetention.BINARY) +annotation class IoDispatcher + +@Module +@InstallIn(SingletonComponent::class) +object CoroutinesModule { + + @Provides + @Singleton + @IoDispatcher + fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO +} diff --git a/ChatApp/wear/src/main/AndroidManifest.xml b/ChatApp/wear/src/main/AndroidManifest.xml index 1ffdcd76..43298159 100644 --- a/ChatApp/wear/src/main/AndroidManifest.xml +++ b/ChatApp/wear/src/main/AndroidManifest.xml @@ -65,9 +65,6 @@ - diff --git a/ChatApp/wear/src/main/kotlin/com/example/chatapp/wear/uicomponents/WearAppFunctionsScreen.kt b/ChatApp/wear/src/main/kotlin/com/example/chatapp/wear/uicomponents/WearAppFunctionsScreen.kt index 618a6a8c..06f11cc1 100644 --- a/ChatApp/wear/src/main/kotlin/com/example/chatapp/wear/uicomponents/WearAppFunctionsScreen.kt +++ b/ChatApp/wear/src/main/kotlin/com/example/chatapp/wear/uicomponents/WearAppFunctionsScreen.kt @@ -69,25 +69,74 @@ fun WearAppFunctionsScreen(viewModel: AppFunctionsViewModel = hiltViewModel()) { ) } } else { - items(uiState.functions) { function -> - SwitchButton( - transformation = SurfaceTransformation(transformationSpec), - modifier = - Modifier - .fillMaxWidth() - .transformedHeight(this, transformationSpec), - checked = function.isEnabled, - onCheckedChange = { enabled -> - viewModel.toggleFunction(function.id, enabled) - }, - label = { - val shortName = function.id.substringAfterLast("#").substringAfterLast(".") - Text(text = shortName) - }, - secondaryLabel = { - Text(text = function.description ?: function.id) - }, - ) + if (uiState.advancedFunctions.isNotEmpty()) { + item { + ListHeader( + modifier = + Modifier + .fillMaxWidth() + .transformedHeight(this, transformationSpec), + transformation = SurfaceTransformation(transformationSpec), + ) { + Text("Advanced Features") + } + } + + items(uiState.advancedFunctions) { function -> + SwitchButton( + transformation = SurfaceTransformation(transformationSpec), + modifier = + Modifier + .fillMaxWidth() + .transformedHeight(this, transformationSpec), + checked = function.isEnabled, + onCheckedChange = { enabled -> + viewModel.toggleFunction(function.id, enabled) + }, + label = { + val shortName = function.id.substringAfterLast("#").substringAfterLast(".") + Text(text = shortName) + }, + secondaryLabel = { + Text(text = function.description ?: function.id) + }, + ) + } + } + + if (uiState.baselineFunctions.isNotEmpty()) { + item { + ListHeader( + modifier = + Modifier + .fillMaxWidth() + .transformedHeight(this, transformationSpec), + transformation = SurfaceTransformation(transformationSpec), + ) { + Text("Standard Functions") + } + } + + items(uiState.baselineFunctions) { function -> + SwitchButton( + transformation = SurfaceTransformation(transformationSpec), + modifier = + Modifier + .fillMaxWidth() + .transformedHeight(this, transformationSpec), + checked = function.isEnabled, + onCheckedChange = { enabled -> + viewModel.toggleFunction(function.id, enabled) + }, + label = { + val shortName = function.id.substringAfterLast("#").substringAfterLast(".") + Text(text = shortName) + }, + secondaryLabel = { + Text(text = function.description ?: function.id) + }, + ) + } } } } diff --git a/ChatApp/wear/src/main/res/xml/app_metadata.xml b/ChatApp/wear/src/main/res/xml/app_metadata.xml index 5f58c854..5509cf31 100644 --- a/ChatApp/wear/src/main/res/xml/app_metadata.xml +++ b/ChatApp/wear/src/main/res/xml/app_metadata.xml @@ -18,9 +18,9 @@ From 1c844fc502a4c021dda167ef1b8b66c2bb52de24 Mon Sep 17 00:00:00 2001 From: Austin Tumlinson Date: Mon, 30 Nov 2026 16:20:30 +0000 Subject: [PATCH 9/9] dynamic function cleanup and toggle availability, gating enhancements, UI toggle, WIP --- .../src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt | 1 - .../kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt | 1 - .../src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt | 1 - 3 files changed, 3 deletions(-) diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt index 4cb17cdf..0a740d90 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/AppFunctionsViewModel.kt @@ -69,7 +69,6 @@ class AppFunctionsViewModel application: Application, private val appFunctionManager: AppFunctionManager?, ) : AndroidViewModel(application) { - val uiState: StateFlow = appFunctionManager ?.observeAppFunctions() diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt index eb8f26ce..0bedaa9e 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt @@ -27,7 +27,6 @@ import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppFunctionModule { - @Provides @Singleton fun provideAppFunctionManager( diff --git a/ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt b/ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt index 8caf629b..d394cdf9 100644 --- a/ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.kt @@ -31,7 +31,6 @@ annotation class IoDispatcher @Module @InstallIn(SingletonComponent::class) object CoroutinesModule { - @Provides @Singleton @IoDispatcher