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/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/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 57d9673e..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..0a740d90 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,9 +67,8 @@ class AppFunctionsViewModel @Inject constructor( application: Application, + private val appFunctionManager: AppFunctionManager?, ) : AndroidViewModel(application) { - private val appFunctionManager = AppFunctionManager.getInstance(application) - val uiState: StateFlow = appFunctionManager ?.observeAppFunctions() @@ -99,7 +102,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 +132,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..0bedaa9e --- /dev/null +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppFunctionModule.kt @@ -0,0 +1,37 @@ +/* + * 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 new file mode 100644 index 00000000..44fbcdbd --- /dev/null +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/appfunctions/AppendDraftMessageSignature.kt @@ -0,0 +1,36 @@ +/* + * 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. + * + * @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 1e53c184..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 @@ -60,7 +60,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". @@ -111,7 +110,6 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { /** * 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. @@ -192,7 +190,6 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { /** * 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. @@ -202,7 +199,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, @@ -235,13 +232,12 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { /** * 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(isDescribedByKDoc = true) + @AppFunctionDeclaration(isEnabled = false, isDescribedByKDoc = true) suspend fun makeCall(endpointValue: String): PendingIntent { val recipient = recipientsRepository.getRecipientById(endpointValue) @@ -252,9 +248,9 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { callManager.startCall(recipient.id) return PendingIntent.getActivity( - this, + this@BaseChatAppFunctionService, 0, - Intent().setClassName(this, "com.example.chatapp.MainActivity") + Intent().setClassName(this@BaseChatAppFunctionService, "com.example.chatapp.MainActivity") .apply { putExtra("nav_route", "call/${recipient.id}") }, PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE, ) @@ -266,7 +262,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, @@ -287,6 +283,25 @@ abstract class BaseChatAppFunctionService : AppFunctionService() { } } + /** + * 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. * 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..d394cdf9 --- /dev/null +++ b/ChatApp/shared/src/main/kotlin/com/example/chatapp/di/CoroutinesModule.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.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/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 @@