Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class AppFunctionsViewModelTest {
@Before
fun setUp() {
application = ApplicationProvider.getApplicationContext()
viewModel = AppFunctionsViewModel(application)
viewModel = AppFunctionsViewModel(application, androidx.appfunctions.AppFunctionManager.getInstance(application))
}

@Test
Expand All @@ -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)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ class AppFunctionInstrumentationTest {
@Test
fun testSend_success() =
runBlocking<Unit> {
appFunctionManager.setAppFunctionEnabled(
ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE,
AppFunctionManager.APP_FUNCTION_STATE_ENABLED,
)
val sendMessageFunctionMetadata =
appFunctionManager
.searchAppFunctions(
Expand Down Expand Up @@ -99,6 +103,10 @@ class AppFunctionInstrumentationTest {
@Test
fun testSend_emptyContent_fails() =
runBlocking<Unit> {
appFunctionManager.setAppFunctionEnabled(
ChatAppFunctionService.FUNCTION_ID_SEND_MESSAGE,
AppFunctionManager.APP_FUNCTION_STATE_ENABLED,
)
val sendMessageFunctionMetadata =
appFunctionManager
.searchAppFunctions(
Expand Down Expand Up @@ -166,4 +174,76 @@ class AppFunctionInstrumentationTest {
),
)
}

@Test
fun testHighSensitivityFunctions_disabledByDefault() =
runBlocking<Unit> {
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<Unit> {
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()
}
}
}
}
3 changes: 3 additions & 0 deletions ChatApp/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@
<property
android:name="android.app.appfunctions.app_metadata"
android:resource="@xml/app_metadata" />
<property
android:name="android.app.appfunctions"
android:value="chat_activity_app_functions.xml" />
</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 = {
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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<AppendDraftMessageSignature>()
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 ->
Expand Down Expand Up @@ -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 =
Expand Down
8 changes: 4 additions & 4 deletions ChatApp/app/src/main/res/xml/app_metadata.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
<AppFunctionAppMetadata xmlns:appfn="http://schemas.android.com/apk/androidx.appfunctions"
appfn:description="Provides functions for managing chat conversations, searching contacts, sending messages, and initiating voice calls.
Operational Patterns:
- Always call 'searchContacts' first to resolve contact or group names to an 'endpointValue' before calling 'send' or 'makeCall'.
- Passing a blank query string to 'searchContacts' retrieves the most recently contacted entities.
- Always call 'searchContacts' first to resolve contact or group names to an 'endpointValue' before calling 'sendMessage', 'fetchSendMessageDetails', or 'makeCall'.
- Query string passed to 'searchContacts' must not be empty or blank.
Constraints:
- Message content cannot be empty or blank when calling 'send'.
- Message content cannot be empty or blank when calling 'sendMessage' or 'fetchSendMessageDetails'.
- Calls and messages must use valid endpointValue identifiers returned by 'searchContacts'.
- Image attachments are supported in 'send' via a list of content URIs."
- Image attachments are supported in 'sendMessage' via a list of content URIs."
appfn:displayDescription="@string/app_function_app_display_description"/>
Loading