diff --git a/.github/workflows/agent.yaml b/.github/workflows/agent.yaml index afccfa80..bbeb3b3f 100644 --- a/.github/workflows/agent.yaml +++ b/.github/workflows/agent.yaml @@ -101,12 +101,22 @@ jobs: working-directory: agent - name: Run instrumentation tests + id: instrumentation-tests run: | ./gradlew :app:pixel7Api37StandardDebugAndroidTest -PGEMINI_API_KEY=dummy_key \ -Pandroid.experimental.testOptions.managedDevices.emulator.showKernelLogging=true \ -Pandroid.testoptions.manageddevices.emulator.gpu="swiftshader_indirect" working-directory: agent + - name: Upload instrumentation test results + if: failure() && steps.instrumentation-tests.outcome == 'failure' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: agent-instrumentation-test-results + path: | + agent/app/build/outputs/androidTest-results/managedDevice + agent/app/build/reports/androidTests/managedDevice + - name: Build Debug and Release APKs run: ./gradlew assembleDebug assembleRelease -PGEMINI_API_KEY=dummy_key working-directory: agent diff --git a/agent/app/src/androidTest/java/com/example/appfunctions/agent/FakeAppFunctionRule.kt b/agent/app/src/androidTest/java/com/example/appfunctions/agent/FakeAppFunctionRule.kt new file mode 100644 index 00000000..e3dec6c7 --- /dev/null +++ b/agent/app/src/androidTest/java/com/example/appfunctions/agent/FakeAppFunctionRule.kt @@ -0,0 +1,199 @@ +/* + * 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.appfunctions.agent + +import android.content.Context +import android.os.ParcelFileDescriptor +import androidx.appfunctions.AppFunctionManager +import androidx.appfunctions.AppFunctionName +import androidx.appfunctions.AppFunctionSearchSpec +import androidx.test.core.app.ApplicationProvider +import androidx.test.platform.app.InstrumentationRegistry +import com.example.appfunctions.agent.data.FakeAppFunctionService +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import org.junit.Assert.fail +import org.junit.rules.ExternalResource +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource + +/** + * Puts the agent's own [FakeAppFunctionService.FUNCTION_ID_FAKE_FUNCTION] in a known state for an + * instrumented test. + * + * Before each test, it adopts the shell identity that reading and executing app functions needs, + * waits until the freshly installed app's functions are indexed (through the same APIs the tests + * call) and resets the function to its default, enabled state. After each test, it resets the + * state again, so a test that disables the function can't affect the next one, and drops the + * shell identity. + */ +class FakeAppFunctionRule : ExternalResource() { + val context: Context = ApplicationProvider.getApplicationContext() + val appFunctionManager: AppFunctionManager = + checkNotNull(AppFunctionManager.getInstance(context)) { + "AppFunctionManager is not available on this device" + } + val functionName = + AppFunctionName(context.packageName, FakeAppFunctionService.FUNCTION_ID_FAKE_FUNCTION) + + private val uiAutomation + get() = InstrumentationRegistry.getInstrumentation().uiAutomation + + override fun before() { + uiAutomation.adoptShellPermissionIdentity(EXECUTE_APP_FUNCTIONS) + try { + runBlocking { + awaitUntil("fakeFunction to be indexed", INDEXING_TIMEOUT, ::describeIndexedFunctions) { + val functions = + appFunctionManager.searchAppFunctions( + AppFunctionSearchSpec(packageNames = setOf(context.packageName)), + ) + functions.any { it.name == functionName } && + appFunctionManager.getAppFunctionStates(listOf(functionName)).isNotEmpty() + } + setEnabledState(AppFunctionManager.APP_FUNCTION_STATE_DEFAULT) + awaitUntil("fakeFunction to be enabled") { + appFunctionManager.getAppFunctionStates(listOf(functionName)).single().isEnabled + } + } + } catch (e: Throwable) { + // after() doesn't run when before() fails. + uiAutomation.dropShellPermissionIdentity() + throw e + } + } + + override fun after() { + try { + runBlocking { setEnabledState(AppFunctionManager.APP_FUNCTION_STATE_DEFAULT) } + } finally { + uiAutomation.dropShellPermissionIdentity() + } + } + + /** Enables or disables the fake function at runtime, as an app does with its own functions. */ + suspend fun setEnabled(enabled: Boolean) { + setEnabledState( + if (enabled) { + AppFunctionManager.APP_FUNCTION_STATE_ENABLED + } else { + AppFunctionManager.APP_FUNCTION_STATE_DISABLED + }, + ) + } + + /** + * Enables or disables the fake function, as [setEnabled] does, and returns the result of + * [awaitChange], which waits until the code under test shows the change. Fails the test after + * [timeout]. + * + * A flow built on [AppFunctionManager.observeAppFunctions] registers its platform observer only + * when it is collected, and the observer isn't notified of earlier changes. + * `GetAppFunctionsUseCase` emits a first result before that, so a change made right after that + * result can be missed. Until [awaitChange] returns, the function is therefore switched to the + * other state and back every [RETOGGLE_INTERVAL]. + */ + suspend fun setEnabledAndAwait( + enabled: Boolean, + timeout: Duration = 30.seconds, + awaitChange: suspend () -> T, + ): T = + coroutineScope { + setEnabled(enabled) + val retoggling = + launch { + while (true) { + delay(RETOGGLE_INTERVAL) + // Not cancellable, so that the function is always left in the requested state. + withContext(NonCancellable) { + setEnabled(!enabled) + setEnabled(enabled) + } + } + } + try { + withTimeout(timeout) { awaitChange() } + } finally { + retoggling.cancelAndJoin() + } + } + + private suspend fun setEnabledState(state: Int) { + appFunctionManager.setAppFunctionEnabled(functionName.functionIdentifier, state) + } + + private fun describeIndexedFunctions(): String { + val command = "cmd app_function list-app-functions --package ${context.packageName}" + val output = + ParcelFileDescriptor.AutoCloseInputStream(uiAutomation.executeShellCommand(command)) + .bufferedReader() + .use { it.readText() } + return "Output of '$command': $output" + } + + private companion object { + const val EXECUTE_APP_FUNCTIONS = "android.permission.EXECUTE_APP_FUNCTIONS" + + /** Indexing a freshly installed app can take a while on a slow emulator. */ + val INDEXING_TIMEOUT = 60.seconds + + /** + * How long a state change may take to show before it is made again. Long enough for the + * observer's notification, the use case's debounce and its queries; making the change again + * while it is still on its way does no harm. + */ + val RETOGGLE_INTERVAL = 5.seconds + } +} + +/** + * Polls [condition] until it is true. Fails the test after [timeout], with [describeState] and the + * last error thrown by [condition], if any. + */ +suspend fun awaitUntil( + description: String, + timeout: Duration = 30.seconds, + describeState: () -> String = { "" }, + condition: suspend () -> Boolean, +) { + val start = TimeSource.Monotonic.markNow() + var lastError: Exception? = null + while (true) { + val isMet = + try { + condition() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + lastError = e + false + } + if (isMet) return + if (start.elapsedNow() > timeout) { + fail("Timed out after $timeout waiting for $description. Last error: $lastError. ${describeState()}") + } + delay(500.milliseconds) + } +} diff --git a/agent/app/src/androidTest/java/com/example/appfunctions/agent/domain/GetAppFunctionStatesUseCaseTest.kt b/agent/app/src/androidTest/java/com/example/appfunctions/agent/domain/GetAppFunctionStatesUseCaseTest.kt index 01c2f708..a91e2716 100644 --- a/agent/app/src/androidTest/java/com/example/appfunctions/agent/domain/GetAppFunctionStatesUseCaseTest.kt +++ b/agent/app/src/androidTest/java/com/example/appfunctions/agent/domain/GetAppFunctionStatesUseCaseTest.kt @@ -15,73 +15,56 @@ */ package com.example.appfunctions.agent.domain -import android.content.Context -import android.os.ParcelFileDescriptor -import androidx.appfunctions.AppFunctionManager -import androidx.appfunctions.AppFunctionName -import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.platform.app.InstrumentationRegistry -import com.example.appfunctions.agent.data.FakeAppFunctionService +import com.example.appfunctions.agent.FakeAppFunctionRule +import com.example.appfunctions.agent.awaitUntil import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionStatesUseCase import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue -import org.junit.Assert.fail -import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class GetAppFunctionStatesUseCaseTest { - private lateinit var context: Context - private lateinit var appFunctionManager: AppFunctionManager - private lateinit var useCase: GetAppFunctionStatesUseCase + @get:Rule + val fakeFunction = FakeAppFunctionRule() - @Before - fun setup() { - context = ApplicationProvider.getApplicationContext() - appFunctionManager = AppFunctionManager.getInstance(context)!! - useCase = GetAppFunctionStatesUseCase(appFunctionManager) + private val useCase by lazy { GetAppFunctionStatesUseCase(fakeFunction.appFunctionManager) } - // Adopt shell permission identity - val uiAutomation = InstrumentationRegistry.getInstrumentation().uiAutomation - uiAutomation.adoptShellPermissionIdentity("android.permission.EXECUTE_APP_FUNCTIONS") + @Test + fun invoke_returnsFakeFunctionState() = + runBlocking { + val result = useCase(listOf(fakeFunction.functionName)) + + val found = result.find { it.functionName == fakeFunction.functionName } + assertNotNull("Should find fakeFunction from ${fakeFunction.functionName}", found) + assertTrue("The function should be enabled", checkNotNull(found).isEnabled) + } - waitForFakeFunctionIndexed() - } + @Test + fun invoke_functionDisabledAtRuntime_returnsDisabledState() = + runBlocking { + fakeFunction.setEnabled(false) - private fun waitForFakeFunctionIndexed() { - val uiAutomation = InstrumentationRegistry.getInstrumentation().uiAutomation - val command = "cmd app_function list-app-functions --package ${context.packageName}" - var output = "" - val timeoutMs = 10_000L - val startTime = System.currentTimeMillis() - while (System.currentTimeMillis() - startTime < timeoutMs) { - output = - ParcelFileDescriptor.AutoCloseInputStream( - uiAutomation.executeShellCommand(command), - ).bufferedReader().use { it.readText() } - if (output.contains("fakeFunction")) { - return + awaitUntil("the use case to report fakeFunction as disabled") { + !useCase(listOf(fakeFunction.functionName)).single().isEnabled } - Thread.sleep(500) } - fail("Timed out waiting for fakeFunction to be indexed. Output of '$command': $output") - } @Test - fun invoke_returnsFakeFunctionState() = + fun invoke_functionReEnabledAtRuntime_returnsEnabledState() = runBlocking { - val targetFunctionName = - AppFunctionName( - context.packageName, - FakeAppFunctionService.FUNCTION_ID_FAKE_FUNCTION, - ) + fakeFunction.setEnabled(false) + awaitUntil("the use case to report fakeFunction as disabled") { + !useCase(listOf(fakeFunction.functionName)).single().isEnabled + } - val result = useCase(listOf(targetFunctionName)) + fakeFunction.setEnabled(true) - val found = result.find { it.functionName == targetFunctionName } - assertTrue("Should find fakeFunction from $targetFunctionName", found != null) - assertTrue("The function should be enabled", checkNotNull(found).isEnabled) + awaitUntil("the use case to report fakeFunction as enabled") { + useCase(listOf(fakeFunction.functionName)).single().isEnabled + } } } diff --git a/agent/app/src/androidTest/java/com/example/appfunctions/agent/domain/GetAppFunctionsUseCaseTest.kt b/agent/app/src/androidTest/java/com/example/appfunctions/agent/domain/GetAppFunctionsUseCaseTest.kt index 52b1cab9..44cb5f84 100644 --- a/agent/app/src/androidTest/java/com/example/appfunctions/agent/domain/GetAppFunctionsUseCaseTest.kt +++ b/agent/app/src/androidTest/java/com/example/appfunctions/agent/domain/GetAppFunctionsUseCaseTest.kt @@ -15,12 +15,11 @@ */ package com.example.appfunctions.agent.domain -import android.content.Context -import android.os.ParcelFileDescriptor -import androidx.appfunctions.AppFunctionManager -import androidx.test.core.app.ApplicationProvider +import androidx.appfunctions.metadata.AppFunctionMetadata +import androidx.appfunctions.metadata.AppFunctionPackageMetadata import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.platform.app.InstrumentationRegistry +import com.example.appfunctions.agent.FakeAppFunctionRule +import com.example.appfunctions.agent.awaitUntil import com.example.appfunctions.agent.data.AgentInternalTools import com.example.appfunctions.agent.data.DataStoreSettingsRepository import com.example.appfunctions.agent.data.ToolDiscoveryTools @@ -28,25 +27,30 @@ import com.example.appfunctions.agent.di.settingsDataStore import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionStatesUseCase import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionsParams import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionsUseCase +import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue -import org.junit.Assert.fail import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class GetAppFunctionsUseCaseTest { - private lateinit var context: Context - private lateinit var appFunctionManager: AppFunctionManager + @get:Rule + val fakeFunction = FakeAppFunctionRule() + private lateinit var useCase: GetAppFunctionsUseCase @Before fun setup() { - context = ApplicationProvider.getApplicationContext() - appFunctionManager = AppFunctionManager.getInstance(context)!! + val context = fakeFunction.context + val appFunctionManager = fakeFunction.appFunctionManager val dataStore = context.settingsDataStore useCase = GetAppFunctionsUseCase( @@ -60,47 +64,16 @@ class GetAppFunctionsUseCaseTest { toolDiscoveryTools = ToolDiscoveryTools(context), ), ) - - // Adopt shell permission identity - InstrumentationRegistry.getInstrumentation() - .uiAutomation - .adoptShellPermissionIdentity("android.permission.EXECUTE_APP_FUNCTIONS") - - waitForFakeFunctionIndexed() - } - - private fun waitForFakeFunctionIndexed() { - val uiAutomation = InstrumentationRegistry.getInstrumentation().uiAutomation - val command = "cmd app_function list-app-functions --package ${context.packageName}" - var output = "" - val timeoutMs = 10_000L - val startTime = System.currentTimeMillis() - while (System.currentTimeMillis() - startTime < timeoutMs) { - output = - ParcelFileDescriptor.AutoCloseInputStream( - uiAutomation.executeShellCommand(command), - ).bufferedReader().use { it.readText() } - if (output.contains("fakeFunction")) { - return - } - Thread.sleep(500) - } - fail("Timed out waiting for fakeFunction to be indexed. Output of '$command': $output") } @Test - fun invoke_returnsFakeFunction() = + fun invoke_returnsFakeFunctionAsGlobalFunction() = runBlocking { - val packageName = context.packageName - val result = useCase().first() - val found = - result.entries.any { (pkg, funcs) -> - pkg.packageName.contains(packageName) && - funcs.any { it.id.contains("fakeFunction") } - } - assertTrue("Should find fakeFunction in a package matching $packageName", found) + val found = result.findFakeFunction() + assertNotNull("Should find fakeFunction in ${fakeFunction.context.packageName}", found) + assertEquals(AppFunctionMetadata.SCOPE_GLOBAL, checkNotNull(found).scope) } @Test @@ -112,9 +85,62 @@ class GetAppFunctionsUseCaseTest { .values .flatten() - assertFalse(tools.any { it.id.contains("fakeFunction") }) + assertFalse(tools.any { it.name == fakeFunction.functionName }) val expandTool = tools.first { it.id == AgentInternalTools.EXPAND_TOOL_DESCRIPTION } - assertTrue(expandTool.description.contains(context.packageName)) + assertTrue(expandTool.description.contains(fakeFunction.context.packageName)) } + + @Test + fun invoke_isEnabledFilter_followsFunctionDisabledAtRuntime() = + runBlocking { + fakeFunction.setEnabled(false) + + awaitUntil("fakeFunction to be returned as disabled") { + useCase(DISABLED_ONLY).first().findFakeFunction() != null + } + assertEquals(null, useCase(ENABLED_ONLY).first().findFakeFunction()) + + fakeFunction.setEnabled(true) + + awaitUntil("fakeFunction to be returned as enabled") { + useCase(ENABLED_ONLY).first().findFakeFunction() != null + } + assertEquals(null, useCase(DISABLED_ONLY).first().findFakeFunction()) + } + + @Test + fun invoke_functionDisabledAtRuntime_emitsWithoutTheFunction() = + runBlocking { + val containsFakeFunction = Channel(Channel.UNLIMITED) + val collector = + launch { + useCase(ENABLED_ONLY).collect { result -> + containsFakeFunction.send(result.findFakeFunction() != null) + } + } + try { + assertTrue( + "The first emission should contain fakeFunction", + containsFakeFunction.receive(), + ) + + // The state change makes the flow emit again, without fakeFunction. + fakeFunction.setEnabledAndAwait(false) { + while (containsFakeFunction.receive()) { + // Skip emissions from before the change. + } + } + } finally { + collector.cancel() + } + } + + private fun Map>.findFakeFunction(): AppFunctionMetadata? = + values.flatten().find { it.name == fakeFunction.functionName } + + private companion object { + val ENABLED_ONLY = GetAppFunctionsParams(isEnabled = true, includeInternalTools = false) + val DISABLED_ONLY = GetAppFunctionsParams(isEnabled = false, includeInternalTools = false) + } } diff --git a/agent/app/src/androidTest/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModelTest.kt b/agent/app/src/androidTest/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModelTest.kt new file mode 100644 index 00000000..49fbc46b --- /dev/null +++ b/agent/app/src/androidTest/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModelTest.kt @@ -0,0 +1,188 @@ +/* + * 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.appfunctions.agent.ui.screens.debugging + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.preferencesDataStoreFile +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.example.appfunctions.agent.FakeAppFunctionRule +import com.example.appfunctions.agent.R +import com.example.appfunctions.agent.data.AgentInternalTools +import com.example.appfunctions.agent.data.DataStoreSettingsRepository +import com.example.appfunctions.agent.data.ToolDiscoveryTools +import com.example.appfunctions.agent.domain.appfunction.AppInfo +import com.example.appfunctions.agent.domain.appfunction.ConvertAppFunctionDataToJsonUseCase +import com.example.appfunctions.agent.domain.appfunction.ConvertInputToAppFunctionDataUseCase +import com.example.appfunctions.agent.domain.appfunction.ExecuteAppFunctionUseCase +import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionStatesUseCase +import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionsUseCase +import com.example.appfunctions.agent.domain.appfunction.GetInstalledAppsUseCase +import com.example.appfunctions.agent.domain.appfunction.GrantAppFunctionUriPermissionsUseCase +import com.example.appfunctions.agent.domain.pendingintent.LaunchPendingIntentUseCase +import com.example.appfunctions.agent.domain.troubleshoot.TroubleshootAppUseCase +import dagger.Lazy +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import kotlin.time.Duration.Companion.seconds + +/** + * Runs [DebuggingViewModel] against the device's AppFunction service, with the agent's own + * `fakeFunction` as the function under test. + */ +@RunWith(AndroidJUnit4::class) +class DebuggingViewModelTest { + @get:Rule + val fakeFunction = FakeAppFunctionRule() + + private val dataStoreScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + private val viewModelStore = ViewModelStore() + private lateinit var dataStoreFile: File + private lateinit var viewModel: DebuggingViewModel + + @Before + fun setUp() { + val context = fakeFunction.context + val appFunctionManager = fakeFunction.appFunctionManager + // A separate settings file, so pinned or disconnected apps on the device don't apply. + dataStoreFile = context.preferencesDataStoreFile("debugging_view_model_test") + dataStoreFile.delete() + val dataStore: DataStore = + PreferenceDataStoreFactory.create(scope = dataStoreScope) { dataStoreFile } + val settingsRepository = DataStoreSettingsRepository(dataStore) + val agentInternalTools = AgentInternalTools(context, dataStore, ToolDiscoveryTools(context)) + val getAppFunctionsUseCase = + GetAppFunctionsUseCase( + appFunctionManager = appFunctionManager, + getAppFunctionStatesUseCase = GetAppFunctionStatesUseCase(appFunctionManager), + settingsRepository = settingsRepository, + agentInternalTools = agentInternalTools, + ) + val factory = + viewModelFactory { + initializer { + DebuggingViewModel( + getAppFunctionsUseCase = getAppFunctionsUseCase, + getAppFunctionStatesUseCase = GetAppFunctionStatesUseCase(appFunctionManager), + convertInputToAppFunctionDataUseCase = ConvertInputToAppFunctionDataUseCase(), + executeAppFunctionUseCase = + ExecuteAppFunctionUseCase( + appFunctionManager = appFunctionManager, + convertAppFunctionDataToJsonUseCase = + ConvertAppFunctionDataToJsonUseCase(), + agentInternalTools = agentInternalTools, + grantAppFunctionUriPermissionsUseCase = + GrantAppFunctionUriPermissionsUseCase(context), + getAppFunctionsUseCase = getAppFunctionsUseCase, + startAppInteractionSessionUseCase = + Lazy { error("This test doesn't execute functions") }, + ), + getInstalledAppsUseCase = GetInstalledAppsUseCase(context), + troubleshootAppUseCase = TroubleshootAppUseCase(context, getAppFunctionsUseCase), + launchPendingIntentUseCase = LaunchPendingIntentUseCase(context), + settingsRepository = settingsRepository, + context = context, + ) + } + } + InstrumentationRegistry.getInstrumentation().runOnMainSync { + viewModel = ViewModelProvider(viewModelStore, factory)[DebuggingViewModel::class.java] + } + } + + @After + fun tearDown() { + InstrumentationRegistry.getInstrumentation().runOnMainSync { viewModelStore.clear() } + dataStoreScope.cancel() + dataStoreFile.delete() + } + + @Test + fun selectedApp_functionDisabledAndReEnabledAtRuntime_updatesStatusWithoutReselecting() = + runBlocking { + val agentApp = awaitSupportedApp(fakeFunction.context.packageName) + withContext(Dispatchers.Main) { viewModel.onAppSelected(agentApp) } + val initialStatus = awaitFakeFunctionStatus { it != null } + assertTrue( + "fakeFunction should start enabled and global: $initialStatus", + initialStatus.isEnabled && !initialStatus.isDynamic, + ) + + val disabledStatus = + fakeFunction.setEnabledAndAwait(false) { + awaitFakeFunctionStatus { it?.isEnabled == false } + } + assertFalse("A disabled function can't run", disabledStatus.canRun) + + val enabledStatus = + fakeFunction.setEnabledAndAwait(true) { + awaitFakeFunctionStatus { it?.isEnabled == true } + } + assertTrue("A re-enabled global function can run", enabledStatus.canRun) + } + + /** Waits until [packageName] is listed as an app with functions, then returns it. */ + private suspend fun awaitSupportedApp(packageName: String): AppInfo = + withTimeout(TIMEOUT) { + viewModel.uiState + .first { state -> state.findSupportedApp(packageName) != null } + .let { state -> checkNotNull(state.findSupportedApp(packageName)) } + } + + private fun DebuggingUiState.findSupportedApp(packageName: String): AppInfo? = + filteredApps.sections + .find { it.titleRes == R.string.debugging_supported } + ?.apps + ?.find { it.packageName == packageName } + + /** Waits until the selected app shows a `fakeFunction` status matching [predicate]. */ + private suspend fun awaitFakeFunctionStatus(predicate: (AppFunctionStatus?) -> Boolean): AppFunctionStatus = + withTimeout(TIMEOUT) { + val state = + viewModel.uiState.first { state -> + val functionsState = + state.searchAppResultState as? SearchAppResultState.FunctionsFoundState + functionsState != null && + predicate(functionsState.functionStatuses[fakeFunction.functionName]) + } + val functionsState = state.searchAppResultState as SearchAppResultState.FunctionsFoundState + checkNotNull(functionsState.functionStatuses[fakeFunction.functionName]) + } + + private companion object { + val TIMEOUT = 30.seconds + } +} diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/AppFunctionItem.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/AppFunctionItem.kt index caded5d2..bf24a326 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/AppFunctionItem.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/AppFunctionItem.kt @@ -65,7 +65,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate +import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow @@ -74,10 +76,14 @@ import androidx.compose.ui.unit.dp import com.example.appfunctions.agent.R import com.example.appfunctions.agent.ui.theme.GoogleSansCodeFontFamily +/** + * A function of the selected app. Shows whether it is disabled or dynamic (activity-scoped) and + * enables Run only when the function can run from this screen. + */ @Composable fun AppFunctionItem( function: AppFunctionMetadata, - isEnabled: Boolean, + status: AppFunctionStatus, expanded: Boolean, inputValues: Map, onExpandedChange: (Boolean) -> Unit, @@ -96,6 +102,7 @@ fun AppFunctionItem( MaterialTheme.colorScheme.surface }, ) + val contentAlpha = if (status.isEnabled) 1f else DISABLED_CONTENT_ALPHA Surface( modifier = modifier.fillMaxWidth(), @@ -114,9 +121,7 @@ fun AppFunctionItem( Row( modifier = Modifier.fillMaxWidth() - .alpha(if (isEnabled) 1f else 0.6f) .clickable( - enabled = isEnabled, interactionSource = interactionSource, indication = null, ) { @@ -135,6 +140,7 @@ fun AppFunctionItem( } Row( + modifier = Modifier.alpha(contentAlpha), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp), ) { @@ -155,21 +161,24 @@ fun AppFunctionItem( overflow = TextOverflow.MiddleEllipsis, modifier = Modifier.weight(1f, fill = false), ) + } - if (!isEnabled) { - Surface( - color = MaterialTheme.colorScheme.surfaceVariant, - shape = MaterialTheme.shapes.extraSmall, - ) { - Text( + // On their own line, so that they don't shorten the function name. + if (!status.isEnabled || status.isDynamic) { + Spacer(Modifier.height(4.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + if (!status.isEnabled) { + StatusChip( text = stringResource(R.string.debugging_disabled), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = - Modifier.padding( - horizontal = 4.dp, - vertical = 2.dp, - ), + containerColor = MaterialTheme.colorScheme.surfaceVariant, + contentColor = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (status.isDynamic) { + StatusChip( + text = stringResource(R.string.debugging_dynamic), + containerColor = MaterialTheme.colorScheme.tertiaryContainer, + contentColor = MaterialTheme.colorScheme.onTertiaryContainer, ) } } @@ -179,6 +188,7 @@ fun AppFunctionItem( AnimatedContent( expanded, + modifier = Modifier.alpha(contentAlpha), transitionSpec = { fadeIn().togetherWith(fadeOut()) }, ) { expanded -> @@ -191,6 +201,16 @@ fun AppFunctionItem( overflow = TextOverflow.MiddleEllipsis, ) } + + val statusDescription = statusDescription(status) + if (statusDescription != null) { + Spacer(Modifier.height(4.dp)) + Text( + text = statusDescription, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } Spacer(Modifier.width(8.dp)) @@ -198,7 +218,6 @@ fun AppFunctionItem( Box( modifier = Modifier.padding(end = 2.dp).size(48.dp).clip(CircleShape).clickable( - enabled = isEnabled, interactionSource = interactionSource, indication = ripple(), ) { @@ -233,7 +252,7 @@ fun AppFunctionItem( // Parameters List Column( - modifier = Modifier.alpha(if (isEnabled) 1f else 0.6f), + modifier = Modifier.alpha(contentAlpha), verticalArrangement = Arrangement.spacedBy(8.dp), ) { for (parameter in function.parameters) { @@ -258,11 +277,27 @@ fun AppFunctionItem( Spacer(modifier = Modifier.height(16.dp)) + if (!status.canRun) { + Text( + text = + stringResource( + if (status.isDynamic) { + R.string.debugging_run_unavailable_dynamic + } else { + R.string.debugging_run_unavailable_disabled + }, + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(bottom = 8.dp), + ) + } + Button( onClick = { onInvoke(inputValues) }, modifier = Modifier.height(48.dp).fillMaxWidth(), colors = ButtonDefaults.buttonColors(), - enabled = isEnabled, + enabled = status.canRun, ) { Icon( imageVector = Icons.Default.PlayArrow, @@ -279,6 +314,49 @@ fun AppFunctionItem( } } +/** Explains a disabled or dynamic [status], or returns `null` for an enabled global function. */ +@Composable +private fun statusDescription(status: AppFunctionStatus): String? { + val registeredActivityCount = status.registeredActivityCount + return when { + registeredActivityCount != null && registeredActivityCount > 0 -> + pluralStringResource( + R.plurals.debugging_status_dynamic_registered, + registeredActivityCount, + registeredActivityCount, + ) + registeredActivityCount != null -> + stringResource(R.string.debugging_status_dynamic_not_registered) + !status.isEnabled -> stringResource(R.string.debugging_status_disabled) + else -> null + } +} + +@Composable +private fun StatusChip( + text: String, + containerColor: Color, + contentColor: Color, +) { + Surface( + color = containerColor, + shape = MaterialTheme.shapes.extraSmall, + ) { + Text( + text = text, + style = MaterialTheme.typography.labelSmall, + color = contentColor, + modifier = + Modifier.padding( + horizontal = 4.dp, + vertical = 2.dp, + ), + ) + } +} + +private const val DISABLED_CONTENT_ALPHA = 0.6f + @Composable private fun ParameterInput( name: String, @@ -334,7 +412,7 @@ fun AppFunctionItemPreview() { AppFunctionItem( function = fakeMetadata, - isEnabled = false, + status = AppFunctionStatus(isEnabled = false), expanded = true, inputValues = emptyMap(), onExpandedChange = {}, @@ -371,7 +449,21 @@ fun AppFunctionItem_NoParams_Preview() { AppFunctionItem( function = fakeMetadata, - isEnabled = true, + status = AppFunctionStatus(isEnabled = true), + expanded = true, + inputValues = emptyMap(), + onExpandedChange = {}, + onInputValuesChange = {}, + onInvoke = {}, + ) +} + +@Preview(showBackground = true) +@Composable +fun AppFunctionItem_DynamicRegistered_Preview() { + AppFunctionItem( + function = createDynamicPreviewFunction(), + status = AppFunctionStatus(isEnabled = true, registeredActivityCount = 2), expanded = true, inputValues = emptyMap(), onExpandedChange = {}, @@ -379,3 +471,45 @@ fun AppFunctionItem_NoParams_Preview() { onInvoke = {}, ) } + +@Preview(showBackground = true) +@Composable +fun AppFunctionItem_DynamicNotRegistered_Preview() { + AppFunctionItem( + function = createDynamicPreviewFunction(), + status = AppFunctionStatus(isEnabled = false, registeredActivityCount = 0), + expanded = false, + inputValues = emptyMap(), + onExpandedChange = {}, + onInputValuesChange = {}, + onInvoke = {}, + ) +} + +private fun createDynamicPreviewFunction(): AppFunctionMetadata = + AppFunctionMetadata( + name = AppFunctionName("com.example.test", "appendDraftMessage"), + schema = null, + parameters = + listOf( + AppFunctionParameterMetadata( + name = "messageText", + isRequired = true, + dataType = AppFunctionStringTypeMetadata(isNullable = false), + description = "The text to append", + ), + ), + response = + AppFunctionResponseMetadata( + valueType = AppFunctionStringTypeMetadata(isNullable = false), + description = "Returns a string", + ), + packageMetadata = + AppFunctionPackageMetadata( + packageName = "com.example.test", + components = AppFunctionComponentsMetadata(), + ), + description = "Appends text to the chat input of the current thread", + deprecation = null, + scope = AppFunctionMetadata.SCOPE_ACTIVITY, + ) diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingUiState.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingUiState.kt index 5c595739..a4dccdec 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingUiState.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingUiState.kt @@ -15,7 +15,9 @@ */ package com.example.appfunctions.agent.ui.screens.debugging +import android.os.Build import androidx.appfunctions.AppFunctionName +import androidx.appfunctions.AppFunctionState import androidx.appfunctions.metadata.AppFunctionMetadata import com.example.appfunctions.agent.domain.appfunction.AppInfo import com.example.appfunctions.agent.domain.appfunction.ExecuteAppFunctionResult @@ -39,9 +41,15 @@ data class AppSection(val titleRes: Int, val apps: List, val showPin: B sealed class SearchAppResultState { object Idle : SearchAppResultState() + /** + * The functions of the selected app. + * + * @property functionStatuses The runtime status of each function. A function without an entry + * has a state that couldn't be read. + */ data class FunctionsFoundState( val functions: List = emptyList(), - val enabledState: Map = emptyMap(), + val functionStatuses: Map = emptyMap(), val functionInputs: Map> = emptyMap(), val executionResult: ExecuteAppFunctionResult? = null, val expandedFunctions: Set = emptySet(), @@ -54,3 +62,46 @@ sealed class SearchAppResultState { val isLoading: Boolean = false, ) : SearchAppResultState() } + +/** + * Runtime status of an app function on the Debugging screen. + * + * @property isEnabled Whether the function can be executed right now. It is false when the app + * disabled the function, the function is disabled by default, or a dynamic function isn't + * registered. + * @property registeredActivityCount For an activity-scoped (dynamic) function, the number of + * activities that register it right now. `null` for a global function. + */ +data class AppFunctionStatus( + val isEnabled: Boolean, + val registeredActivityCount: Int? = null, +) { + /** Whether the function is activity-scoped, i.e. registered at runtime by an activity. */ + val isDynamic: Boolean + get() = registeredActivityCount != null + + /** + * Whether the Debugging screen can run the function. An activity-scoped function runs only in + * an activity that registers it, which this screen can't target. + */ + val canRun: Boolean + get() = isEnabled && !isDynamic + + companion object { + /** Builds the status of [function] from its runtime [state]. */ + fun from( + function: AppFunctionMetadata, + state: AppFunctionState, + ): AppFunctionStatus = + AppFunctionStatus( + isEnabled = state.isEnabled, + registeredActivityCount = + if (function.scope == AppFunctionMetadata.SCOPE_ACTIVITY) { + // Activity-scoped functions exist only on API 37+. + if (Build.VERSION.SDK_INT >= 37) state.activityIds?.size ?: 0 else 0 + } else { + null + }, + ) + } +} diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModel.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModel.kt index b76efd54..3759b605 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModel.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModel.kt @@ -38,6 +38,7 @@ import com.example.appfunctions.agent.domain.pendingintent.LaunchPendingIntentUs import com.example.appfunctions.agent.domain.troubleshoot.TroubleshootAppUseCase import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -93,6 +94,7 @@ class DebuggingViewModel private fun loadAppFunctions() { viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } + // Emits again when functions or their states change at runtime. getAppFunctionsUseCase( GetAppFunctionsParams(includeInternalTools = false), ).collect { appFunctionsMap -> @@ -101,6 +103,7 @@ class DebuggingViewModel allAppFunctions = appFunctionsMap allAppFunctionStates = appFunctionStates.associateBy { it.functionName } updateAppsGroupState() + refreshSelectedAppFunctions() } } } @@ -119,31 +122,65 @@ class DebuggingViewModel } } + /** + * Shows the latest functions and states of the selected app, so that a function enabled or + * disabled at runtime, a dynamic function that is registered or unregistered, and added or + * removed functions show without selecting the app again. Inputs, expanded functions and an + * open result are kept. + */ + private fun refreshSelectedAppFunctions() { + val packageName = _uiState.value.selectedApp?.packageName ?: return + // An update without the app (e.g. while it is reinstalled) keeps the last list. + val functions = findFunctions(packageName) ?: return + val functionStatuses = buildFunctionStatuses(functions) + updateFunctionsFoundState { + it.copy(functions = functions, functionStatuses = functionStatuses) + } + } + + private fun findFunctions(packageName: String): List? = + allAppFunctions.entries.find { it.key.packageName == packageName }?.value + + private fun buildFunctionStatuses(functions: List): Map = + buildMap { + for (function in functions) { + val state = allAppFunctionStates[function.name] + if (state == null) { + Log.w(TAG, "Unable to find enabled state for ${function.name}") + } else { + put(function.name, AppFunctionStatus.from(function, state)) + } + } + } + + /** Applies [transform] to the functions state currently shown, if any. */ + private fun updateFunctionsFoundState( + transform: (SearchAppResultState.FunctionsFoundState) -> SearchAppResultState.FunctionsFoundState, + ) { + _uiState.update { state -> + val searchAppResultState = state.searchAppResultState + if (searchAppResultState is SearchAppResultState.FunctionsFoundState) { + state.copy(searchAppResultState = transform(searchAppResultState)) + } else { + state + } + } + } + /** Handles app selection. */ fun onAppSelected(appInfo: AppInfo) { - val functions = - allAppFunctions.entries.find { it.key.packageName == appInfo.packageName }?.value + val functions = findFunctions(appInfo.packageName) if (functions == null) { runTroubleshooting(appInfo.packageName) } else { - val enabledStates = - buildMap { - for (function in functions) { - val enabledState = allAppFunctionStates[function.name] - if (enabledState == null) { - Log.w(TAG, "Unable to find enabled state for ${function.name}") - } else { - put(function.name, enabledState.isEnabled) - } - } - } + val functionStatuses = buildFunctionStatuses(functions) _uiState.update { state -> state.copy( selectedApp = appInfo, searchAppResultState = SearchAppResultState.FunctionsFoundState( functions = functions, - enabledState = enabledStates, + functionStatuses = functionStatuses, ), ) } @@ -176,16 +213,8 @@ class DebuggingViewModel functionId: String, inputs: Map, ) { - _uiState.update { state -> - val currentSearchAppResultState = state.searchAppResultState - if (currentSearchAppResultState !is SearchAppResultState.FunctionsFoundState) return - state.copy( - searchAppResultState = - currentSearchAppResultState.copy( - functionInputs = - currentSearchAppResultState.functionInputs + (functionId to inputs), - ), - ) + updateFunctionsFoundState { + it.copy(functionInputs = it.functionInputs + (functionId to inputs)) } } @@ -194,20 +223,14 @@ class DebuggingViewModel functionId: String, expanded: Boolean, ) { - _uiState.update { state -> - val currentSearchAppResultState = state.searchAppResultState - if (currentSearchAppResultState !is SearchAppResultState.FunctionsFoundState) return - val currentExpanded = currentSearchAppResultState.expandedFunctions - val newExpanded = + updateFunctionsFoundState { + val expandedFunctions = if (expanded) { - currentExpanded + functionId + it.expandedFunctions + functionId } else { - currentExpanded - functionId + it.expandedFunctions - functionId } - state.copy( - searchAppResultState = - currentSearchAppResultState.copy(expandedFunctions = newExpanded), - ) + it.copy(expandedFunctions = expandedFunctions) } } @@ -218,6 +241,7 @@ class DebuggingViewModel val inputs = currentSearchAppResultState.functionInputs[function.id] ?: emptyMap() viewModelScope.launch { + // Results go to the latest state: the functions may have been refreshed meanwhile. try { val appFunctionDataResult = withContext(Dispatchers.Default) { @@ -235,43 +259,34 @@ class DebuggingViewModel parameters = appFunctionData, threadId = DEBUG_THREAD_ID, ) - _uiState.update { + updateFunctionsFoundState { it.copy( - searchAppResultState = - currentSearchAppResultState.copy( - executionResult = result, - executedFunction = function, - executedInputs = inputs, - ), + executionResult = result, + executedFunction = function, + executedInputs = inputs, ) } } .onFailure { error -> - _uiState.update { + updateFunctionsFoundState { it.copy( - searchAppResultState = - currentSearchAppResultState.copy( - executionResult = - ExecuteAppFunctionResult.Error( - Exception( - error.message ?: "Failed to convert input", - ), - ), - executedFunction = function, - executedInputs = inputs, + executionResult = + ExecuteAppFunctionResult.Error( + Exception(error.message ?: "Failed to convert input"), ), + executedFunction = function, + executedInputs = inputs, ) } } + } catch (e: CancellationException) { + throw e } catch (e: Exception) { - _uiState.update { + updateFunctionsFoundState { it.copy( - searchAppResultState = - currentSearchAppResultState.copy( - executionResult = ExecuteAppFunctionResult.Error(e), - executedFunction = function, - executedInputs = inputs, - ), + executionResult = ExecuteAppFunctionResult.Error(e), + executedFunction = function, + executedInputs = inputs, ) } } @@ -280,38 +295,28 @@ class DebuggingViewModel /** Clears the last execution result or error message. */ fun clearResult() { - val currentSearchAppResultState = _uiState.value.searchAppResultState - if (currentSearchAppResultState !is SearchAppResultState.FunctionsFoundState) return - _uiState.update { + updateFunctionsFoundState { it.copy( - searchAppResultState = - currentSearchAppResultState.copy( - executionResult = null, - executedFunction = null, - executedInputs = emptyMap(), - ), + executionResult = null, + executedFunction = null, + executedInputs = emptyMap(), ) } } /** Handles launching a PendingIntent. */ fun launchPendingIntent(pendingIntent: PendingIntent) { - val currentSearchAppResultState = _uiState.value.searchAppResultState - if (currentSearchAppResultState !is SearchAppResultState.FunctionsFoundState) return + if (_uiState.value.searchAppResultState !is SearchAppResultState.FunctionsFoundState) return viewModelScope.launch { val result = launchPendingIntentUseCase(pendingIntent) if (result.isFailure) { - _uiState.update { state -> - state.copy( - searchAppResultState = - currentSearchAppResultState.copy( - executionResult = - ExecuteAppFunctionResult.Error( - Exception( - result.exceptionOrNull()?.message - ?: "Failed to launch action", - ), - ), + updateFunctionsFoundState { + it.copy( + executionResult = + ExecuteAppFunctionResult.Error( + Exception( + result.exceptionOrNull()?.message ?: "Failed to launch action", + ), ), ) } diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/FunctionsFoundContent.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/FunctionsFoundContent.kt index 07d95ff6..cc5212e8 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/FunctionsFoundContent.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/debugging/FunctionsFoundContent.kt @@ -98,8 +98,8 @@ fun FunctionsFoundContent( items = state.functions, key = { function -> function.id }, ) { function -> - val isEnabled = state.enabledState[function.name] - if (isEnabled == null) { + val status = state.functionStatuses[function.name] + if (status == null) { AppFunctionErrorItem(function = function) return@items } @@ -108,7 +108,7 @@ fun FunctionsFoundContent( AppFunctionItem( function = function, - isEnabled = isEnabled, + status = status, expanded = expanded, inputValues = inputValues, onExpandedChange = { isExpanded -> @@ -296,7 +296,7 @@ fun AppFunctionErrorItem( color = MaterialTheme.colorScheme.onErrorContainer, ) Text( - text = "Unable to determine enabled state", + text = stringResource(R.string.debugging_state_unknown), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onErrorContainer, ) @@ -379,7 +379,7 @@ fun FunctionsFoundContentPreview() { val dummyState = SearchAppResultState.FunctionsFoundState( functions = listOf(function1, function2), - enabledState = mapOf(function1Name to true), + functionStatuses = mapOf(function1Name to AppFunctionStatus(isEnabled = true)), expandedFunctions = emptySet(), functionInputs = emptyMap(), executionResult = null, diff --git a/agent/app/src/main/res/values/strings.xml b/agent/app/src/main/res/values/strings.xml index 71e3d6e1..2fd66d8d 100644 --- a/agent/app/src/main/res/values/strings.xml +++ b/agent/app/src/main/res/values/strings.xml @@ -42,6 +42,16 @@ Expand function Collapse function Disabled + Dynamic + Turned off by the app, or not registered + + Registered by %d activity + Registered by %d activities + + Not registered: open the activity that provides it + Disabled functions can\'t run. + The Debug tab can\'t run activity-scoped functions yet. + Unable to determine enabled state Edit Execution Result Confirm diff --git a/agent/app/src/screenshotTest/kotlin/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTest.kt b/agent/app/src/screenshotTest/kotlin/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTest.kt index dee3717b..8b9f9caa 100644 --- a/agent/app/src/screenshotTest/kotlin/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTest.kt +++ b/agent/app/src/screenshotTest/kotlin/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTest.kt @@ -15,6 +15,7 @@ */ package com.example.appfunctions.agent.ui.screens.debugging +import androidx.appfunctions.AppFunctionName import androidx.appfunctions.metadata.AppFunctionArrayTypeMetadata import androidx.appfunctions.metadata.AppFunctionBooleanTypeMetadata import androidx.appfunctions.metadata.AppFunctionComponentsMetadata @@ -24,6 +25,7 @@ import androidx.appfunctions.metadata.AppFunctionIntTypeMetadata import androidx.appfunctions.metadata.AppFunctionLongTypeMetadata import androidx.appfunctions.metadata.AppFunctionMetadata import androidx.appfunctions.metadata.AppFunctionObjectTypeMetadata +import androidx.appfunctions.metadata.AppFunctionPackageMetadata import androidx.appfunctions.metadata.AppFunctionParameterMetadata import androidx.appfunctions.metadata.AppFunctionReferenceTypeMetadata import androidx.appfunctions.metadata.AppFunctionResponseMetadata @@ -86,7 +88,7 @@ fun DebuggingScreenAppSelectedScreenshotPreview() { searchAppResultState = SearchAppResultState.FunctionsFoundState( functions = listOf(function), - enabledState = mapOf(function.name to true), + functionStatuses = mapOf(function.name to AppFunctionStatus(isEnabled = true)), ), ) AppFunctionsAgentTheme { @@ -123,7 +125,7 @@ fun DebuggingScreenFunctionExpandedScreenshotPreview() { searchAppResultState = SearchAppResultState.FunctionsFoundState( functions = listOf(function), - enabledState = mapOf(function.name to true), + functionStatuses = mapOf(function.name to AppFunctionStatus(isEnabled = true)), expandedFunctions = setOf(function.id), ), ) @@ -161,7 +163,7 @@ fun DebuggingScreenFunctionExpandedWithInputsScreenshotPreview() { searchAppResultState = SearchAppResultState.FunctionsFoundState( functions = listOf(function), - enabledState = mapOf(function.name to true), + functionStatuses = mapOf(function.name to AppFunctionStatus(isEnabled = true)), expandedFunctions = setOf(function.id), functionInputs = mapOf( @@ -249,7 +251,7 @@ fun DebuggingScreenFunctionWithEnumScreenshotPreview() { searchAppResultState = SearchAppResultState.FunctionsFoundState( functions = listOf(function), - enabledState = mapOf(function.name to true), + functionStatuses = mapOf(function.name to AppFunctionStatus(isEnabled = true)), expandedFunctions = setOf(function.id), ), ) @@ -271,6 +273,122 @@ fun DebuggingScreenFunctionWithEnumScreenshotPreview() { } } +@PreviewTest +@Preview(showBackground = true) +@Composable +fun DebuggingScreenFunctionStatesScreenshotPreview() { + val enabled = createStatusFunction("sendMessage") + val disabled = createStatusFunction("deleteThread") + val dynamicRegistered = + createStatusFunction("appendDraftMessage", AppFunctionMetadata.SCOPE_ACTIVITY) + val dynamicNotRegistered = + createStatusFunction("insertIntoCurrentThread", AppFunctionMetadata.SCOPE_ACTIVITY) + FunctionsScreenshot( + SearchAppResultState.FunctionsFoundState( + functions = listOf(enabled, disabled, dynamicRegistered, dynamicNotRegistered), + functionStatuses = + mapOf( + enabled.name to AppFunctionStatus(isEnabled = true), + disabled.name to AppFunctionStatus(isEnabled = false), + dynamicRegistered.name to + AppFunctionStatus(isEnabled = true, registeredActivityCount = 1), + dynamicNotRegistered.name to + AppFunctionStatus(isEnabled = false, registeredActivityCount = 0), + ), + ), + ) +} + +@PreviewTest +@Preview(showBackground = true) +@Composable +fun DebuggingScreenDisabledFunctionExpandedScreenshotPreview() { + val function = createStatusFunction("deleteThread") + FunctionsScreenshot( + SearchAppResultState.FunctionsFoundState( + functions = listOf(function), + functionStatuses = mapOf(function.name to AppFunctionStatus(isEnabled = false)), + expandedFunctions = setOf(function.id), + ), + ) +} + +@PreviewTest +@Preview(showBackground = true) +@Composable +fun DebuggingScreenDynamicFunctionExpandedScreenshotPreview() { + val function = createStatusFunction("appendDraftMessage", AppFunctionMetadata.SCOPE_ACTIVITY) + FunctionsScreenshot( + SearchAppResultState.FunctionsFoundState( + functions = listOf(function), + functionStatuses = + mapOf(function.name to AppFunctionStatus(isEnabled = true, registeredActivityCount = 2)), + expandedFunctions = setOf(function.id), + ), + ) +} + +@Composable +private fun FunctionsScreenshot(state: SearchAppResultState.FunctionsFoundState) { + val app = AppInfo("com.example.test", "Test App", null) + val dummyState = + DebuggingUiState( + filteredApps = + AppsGroupState( + sections = listOf(AppSection(R.string.debugging_supported, listOf(app), true)), + ), + selectedApp = app, + searchAppResultState = state, + ) + AppFunctionsAgentTheme { + Box(Modifier.background(MaterialTheme.colorScheme.background)) { + DebuggingScreenContent( + uiState = dummyState, + onSearchQueryChanged = {}, + onAppSelected = {}, + onClearSelectedApp = {}, + onFunctionInputsChange = { _, _ -> }, + onInvoke = {}, + onClearResult = {}, + onFunctionExpandedChange = { _, _ -> }, + onLaunchPendingIntent = {}, + onTogglePin = {}, + ) + } + } +} + +private fun createStatusFunction( + id: String, + scope: Int = AppFunctionMetadata.SCOPE_GLOBAL, +): AppFunctionMetadata = + AppFunctionMetadata( + name = AppFunctionName("com.example.test", id), + schema = null, + parameters = + listOf( + AppFunctionParameterMetadata( + name = "threadId", + isRequired = true, + dataType = AppFunctionStringTypeMetadata(isNullable = false), + description = "String param", + ), + ), + response = + AppFunctionResponseMetadata( + valueType = AppFunctionStringTypeMetadata(isNullable = false), + description = "Returns a string", + ), + packageMetadata = + AppFunctionPackageMetadata( + packageName = "com.example.test", + components = AppFunctionComponentsMetadata(emptyMap()), + ), + description = "Function description", + deprecation = null, + scope = scope, + ) + private fun createFakeFunction(): AppFunctionMetadata { val stringType = AppFunctionStringTypeMetadata(isNullable = false) val intType = AppFunctionIntTypeMetadata(isNullable = false) diff --git a/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDisabledFunctionExpandedScreenshotPreview_748aa731_0.png b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDisabledFunctionExpandedScreenshotPreview_748aa731_0.png new file mode 100644 index 00000000..aca70690 Binary files /dev/null and b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDisabledFunctionExpandedScreenshotPreview_748aa731_0.png differ diff --git a/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDynamicFunctionExpandedScreenshotPreview_748aa731_0.png b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDynamicFunctionExpandedScreenshotPreview_748aa731_0.png new file mode 100644 index 00000000..04d14949 Binary files /dev/null and b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDynamicFunctionExpandedScreenshotPreview_748aa731_0.png differ diff --git a/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenFunctionStatesScreenshotPreview_748aa731_0.png b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenFunctionStatesScreenshotPreview_748aa731_0.png new file mode 100644 index 00000000..72599220 Binary files /dev/null and b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenFunctionStatesScreenshotPreview_748aa731_0.png differ diff --git a/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDisabledFunctionExpandedScreenshotPreview_748aa731_0.png b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDisabledFunctionExpandedScreenshotPreview_748aa731_0.png new file mode 100644 index 00000000..aca70690 Binary files /dev/null and b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDisabledFunctionExpandedScreenshotPreview_748aa731_0.png differ diff --git a/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDynamicFunctionExpandedScreenshotPreview_748aa731_0.png b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDynamicFunctionExpandedScreenshotPreview_748aa731_0.png new file mode 100644 index 00000000..04d14949 Binary files /dev/null and b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenDynamicFunctionExpandedScreenshotPreview_748aa731_0.png differ diff --git a/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenFunctionStatesScreenshotPreview_748aa731_0.png b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenFunctionStatesScreenshotPreview_748aa731_0.png new file mode 100644 index 00000000..72599220 Binary files /dev/null and b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/debugging/DebuggingScreenScreenshotTestKt/DebuggingScreenFunctionStatesScreenshotPreview_748aa731_0.png differ diff --git a/agent/app/src/test/java/com/example/appfunctions/agent/data/AndroidLiveAudioSessionTest.kt b/agent/app/src/test/java/com/example/appfunctions/agent/data/AndroidLiveAudioSessionTest.kt index 4410aed4..b54a66c1 100644 --- a/agent/app/src/test/java/com/example/appfunctions/agent/data/AndroidLiveAudioSessionTest.kt +++ b/agent/app/src/test/java/com/example/appfunctions/agent/data/AndroidLiveAudioSessionTest.kt @@ -256,7 +256,8 @@ class AndroidLiveAudioSessionTest { assertTrue(flushedLatch.await(2, TimeUnit.SECONDS)) verify(atLeast = 1) { mockTrack.pause() } verify(atLeast = 1) { mockTrack.flush() } - verify(atLeast = 2) { mockTrack.play() } + // The playback thread calls play() again after flush(), so wait for it. + verify(timeout = 2_000, atLeast = 2) { mockTrack.play() } session.release() } @@ -506,8 +507,11 @@ class AndroidLiveAudioSessionTest { session.release() } releaseCaller.start() - // Spin briefly until releaseCaller flips isReleased (before blocking on stateLock) - Thread.sleep(30) + // release() flips isReleased before it blocks on stateLock, which start() holds. + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2) + while (releaseCaller.state != Thread.State.BLOCKED && System.nanoTime() < deadline) { + Thread.yield() + } releaseIssuedLatch.countDown() releaseCaller.join(2000) } diff --git a/agent/app/src/test/java/com/example/appfunctions/agent/domain/appfunction/GetAppFunctionsUseCaseTest.kt b/agent/app/src/test/java/com/example/appfunctions/agent/domain/appfunction/GetAppFunctionsUseCaseTest.kt index 2e294e2c..60179172 100644 --- a/agent/app/src/test/java/com/example/appfunctions/agent/domain/appfunction/GetAppFunctionsUseCaseTest.kt +++ b/agent/app/src/test/java/com/example/appfunctions/agent/domain/appfunction/GetAppFunctionsUseCaseTest.kt @@ -18,6 +18,7 @@ package com.example.appfunctions.agent.domain.appfunction import androidx.appfunctions.AppFunctionManager import androidx.appfunctions.AppFunctionName import androidx.appfunctions.AppFunctionState +import androidx.appfunctions.AppFunctionsChangeEvent import androidx.appfunctions.metadata.AppFunctionComponentsMetadata import androidx.appfunctions.metadata.AppFunctionMetadata import androidx.appfunctions.metadata.AppFunctionPackageMetadata @@ -27,9 +28,13 @@ import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue @@ -250,6 +255,83 @@ class GetAppFunctionsUseCaseTest { assertTrue(withoutInternal.isEmpty()) } + @Test + fun `metadata change event searches again and emits the changed functions`() = + runTest { + val notesPkg = createPackage("com.example.notes") + val createNoteTool = createTool(notesPkg, "com.example.notes.createNote") + val deleteNoteTool = createTool(notesPkg, "com.example.notes.deleteNote") + var installedTools = listOf(createNoteTool) + coEvery { appFunctionManager.searchAppFunctions(any()) } answers { installedTools } + every { appFunctionManager.observeAppFunctions() } returns + flow { + // The app is updated with a new function after the first search. + installedTools = listOf(createNoteTool, deleteNoteTool) + emit(AppFunctionsChangeEvent.MetadataChanged(setOf(notesPkg.packageName))) + awaitCancellation() + } + + val (beforeChange, afterChange) = + useCase(GetAppFunctionsParams(includeInternalTools = false)).take(2).toList() + + assertEquals(mapOf(notesPkg to listOf(createNoteTool)), beforeChange) + assertEquals(mapOf(notesPkg to listOf(createNoteTool, deleteNoteTool)), afterChange) + } + + @Test + fun `isEnabled filter drops a function disabled at runtime after a states change event`() = + runTest { + val notesPkg = createPackage("com.example.notes") + val notesTool = createTool(notesPkg, "com.example.notes.createNote") + var isNotesToolEnabled = true + coEvery { appFunctionManager.searchAppFunctions(any()) } returns listOf(notesTool) + coEvery { getAppFunctionStatesUseCase(any()) } answers { + firstArg>().map { name -> + createState(name, isEnabled = isNotesToolEnabled) + } + } + every { appFunctionManager.observeAppFunctions() } returns + flow { + // The app disables the function after the first search. + isNotesToolEnabled = false + emit(AppFunctionsChangeEvent.StatesChanged(setOf(notesTool.name))) + awaitCancellation() + } + + val (beforeChange, afterChange) = + useCase(GetAppFunctionsParams(isEnabled = true)).take(2).toList() + + assertEquals(mapOf(notesPkg to listOf(notesTool)), beforeChange) + assertTrue(afterChange.isEmpty()) + } + + @Test + fun `isEnabled filter adds a function enabled at runtime after a states change event`() = + runTest { + val notesPkg = createPackage("com.example.notes") + val notesTool = createTool(notesPkg, "com.example.notes.createNote") + var isNotesToolEnabled = false + coEvery { appFunctionManager.searchAppFunctions(any()) } returns listOf(notesTool) + coEvery { getAppFunctionStatesUseCase(any()) } answers { + firstArg>().map { name -> + createState(name, isEnabled = isNotesToolEnabled) + } + } + every { appFunctionManager.observeAppFunctions() } returns + flow { + // The app enables the function after the first search. + isNotesToolEnabled = true + emit(AppFunctionsChangeEvent.StatesChanged(setOf(notesTool.name))) + awaitCancellation() + } + + val (beforeChange, afterChange) = + useCase(GetAppFunctionsParams(isEnabled = true)).take(2).toList() + + assertTrue(beforeChange.isEmpty()) + assertEquals(mapOf(notesPkg to listOf(notesTool)), afterChange) + } + private fun createPackage(packageName: String): AppFunctionPackageMetadata = AppFunctionPackageMetadata( packageName = packageName, diff --git a/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/debugging/AppFunctionStatusTest.kt b/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/debugging/AppFunctionStatusTest.kt new file mode 100644 index 00000000..ef8efcca --- /dev/null +++ b/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/debugging/AppFunctionStatusTest.kt @@ -0,0 +1,124 @@ +/* + * 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.appfunctions.agent.ui.screens.debugging + +import androidx.appfunctions.AppFunctionName +import androidx.appfunctions.AppFunctionState +import androidx.appfunctions.metadata.AppFunctionComponentsMetadata +import androidx.appfunctions.metadata.AppFunctionMetadata +import androidx.appfunctions.metadata.AppFunctionPackageMetadata +import androidx.appfunctions.metadata.AppFunctionResponseMetadata +import androidx.appfunctions.metadata.AppFunctionStringTypeMetadata +import io.mockk.every +import io.mockk.mockk +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class AppFunctionStatusTest { + @Test + fun `from enabled global function can run`() { + val status = + AppFunctionStatus.from( + createFunction(AppFunctionMetadata.SCOPE_GLOBAL), + createState(isEnabled = true), + ) + + assertEquals(AppFunctionStatus(isEnabled = true, registeredActivityCount = null), status) + assertFalse(status.isDynamic) + assertTrue(status.canRun) + } + + @Test + fun `from disabled global function cannot run`() { + val status = + AppFunctionStatus.from( + createFunction(AppFunctionMetadata.SCOPE_GLOBAL), + createState(isEnabled = false), + ) + + assertEquals(AppFunctionStatus(isEnabled = false, registeredActivityCount = null), status) + assertFalse(status.isDynamic) + assertFalse(status.canRun) + } + + @Test + fun `from activity-scoped function is dynamic and cannot run`() { + val status = + AppFunctionStatus.from( + createFunction(AppFunctionMetadata.SCOPE_ACTIVITY), + createState(isEnabled = true), + ) + + // The registering activities can only be read on API 37+, so SDK 34 reports none. + assertEquals(AppFunctionStatus(isEnabled = true, registeredActivityCount = 0), status) + assertTrue(status.isDynamic) + assertFalse(status.canRun) + } + + @Test + fun `dynamic function registered by activities cannot run`() { + val status = AppFunctionStatus(isEnabled = true, registeredActivityCount = 2) + + assertTrue(status.isDynamic) + assertFalse(status.canRun) + } + + @Test + fun `unregistered dynamic function cannot run`() { + val status = AppFunctionStatus(isEnabled = false, registeredActivityCount = 0) + + assertTrue(status.isDynamic) + assertFalse(status.canRun) + } + + @Test + fun `enabled global function can run`() { + val status = AppFunctionStatus(isEnabled = true, registeredActivityCount = null) + + assertFalse(status.isDynamic) + assertTrue(status.canRun) + } + + private fun createFunction(scope: Int): AppFunctionMetadata = + AppFunctionMetadata( + name = AppFunctionName(PACKAGE_NAME, "test_function"), + schema = null, + parameters = emptyList(), + response = AppFunctionResponseMetadata(valueType = AppFunctionStringTypeMetadata(isNullable = false)), + packageMetadata = + AppFunctionPackageMetadata( + packageName = PACKAGE_NAME, + components = AppFunctionComponentsMetadata(), + ), + scope = scope, + ) + + private fun createState(isEnabled: Boolean): AppFunctionState = + mockk().apply { + every { this@apply.isEnabled } returns isEnabled + } + + private companion object { + const val PACKAGE_NAME = "com.example.app" + } +} diff --git a/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModelTest.kt b/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModelTest.kt index fa40f3ca..45f9cfc4 100644 --- a/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModelTest.kt +++ b/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/debugging/DebuggingViewModelTest.kt @@ -21,15 +21,20 @@ import android.content.pm.ApplicationInfo import android.content.pm.PackageInfo import android.graphics.Color import android.graphics.drawable.ColorDrawable +import androidx.appfunctions.AppFunctionData import androidx.appfunctions.AppFunctionName import androidx.appfunctions.AppFunctionState +import androidx.appfunctions.metadata.AppFunctionComponentsMetadata import androidx.appfunctions.metadata.AppFunctionMetadata import androidx.appfunctions.metadata.AppFunctionPackageMetadata +import androidx.appfunctions.metadata.AppFunctionResponseMetadata +import androidx.appfunctions.metadata.AppFunctionStringTypeMetadata import androidx.test.core.app.ApplicationProvider import com.example.appfunctions.agent.R import com.example.appfunctions.agent.data.SettingsRepository import com.example.appfunctions.agent.domain.appfunction.AppInfo import com.example.appfunctions.agent.domain.appfunction.ConvertInputToAppFunctionDataUseCase +import com.example.appfunctions.agent.domain.appfunction.ExecuteAppFunctionResult import com.example.appfunctions.agent.domain.appfunction.ExecuteAppFunctionUseCase import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionStatesUseCase import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionsParams @@ -40,8 +45,11 @@ import com.example.appfunctions.agent.domain.troubleshoot.TroubleshootAppUseCase import io.mockk.coEvery import io.mockk.every import io.mockk.mockk +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle @@ -50,6 +58,9 @@ import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -76,6 +87,17 @@ class DebuggingViewModelTest { private lateinit var viewModel: DebuggingViewModel private lateinit var context: Context + private val testAppPackage = + AppFunctionPackageMetadata( + packageName = TEST_PACKAGE_NAME, + components = AppFunctionComponentsMetadata(), + ) + private val testApp = AppInfo(TEST_PACKAGE_NAME, TEST_PACKAGE_NAME, null) + + /** The functions of all apps. Emit again to change them at runtime. */ + private val appFunctionsFlow = + MutableSharedFlow>>(replay = 1) + @Before fun setup() { Dispatchers.setMain(testDispatcher) @@ -500,8 +522,301 @@ class DebuggingViewModelTest { val functionsState = state.searchAppResultState as SearchAppResultState.FunctionsFoundState assertEquals( - mapOf(enabledFunctionName to true, disabledFunctionName to false), - functionsState.enabledState, + mapOf( + enabledFunctionName to AppFunctionStatus(isEnabled = true), + disabledFunctionName to AppFunctionStatus(isEnabled = false), + ), + functionsState.functionStatuses, + ) + } + + @Test + fun `function disabled at runtime shows as disabled without selecting the app again`() = + runTest { + val function = createFunction("test_function") + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns appFunctionsFlow + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(function))) + viewModel = createViewModel() + advanceUntilIdle() + viewModel.onAppSelected(testApp) + assertEquals( + mapOf(function.name to AppFunctionStatus(isEnabled = true)), + functionsFoundState().functionStatuses, + ) + + coEvery { mockGetAppFunctionStatesUseCase(any()) } returns + listOf(createState(function.name, isEnabled = false)) + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(function))) + advanceUntilIdle() + + assertEquals( + mapOf(function.name to AppFunctionStatus(isEnabled = false)), + functionsFoundState().functionStatuses, + ) + } + + @Test + fun `functions added and removed at runtime are shown and inputs and expanded functions are kept`() = + runTest { + val keptFunction = createFunction("kept_function") + val removedFunction = createFunction("removed_function") + val addedFunction = createFunction("added_function") + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns appFunctionsFlow + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(keptFunction, removedFunction))) + viewModel = createViewModel() + advanceUntilIdle() + viewModel.onAppSelected(testApp) + val inputs = mapOf("param1" to "value1") + viewModel.onFunctionInputsChange(keptFunction.id, inputs) + viewModel.onFunctionExpandedChange(keptFunction.id, expanded = true) + + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(keptFunction, addedFunction))) + advanceUntilIdle() + + val functionsState = functionsFoundState() + assertEquals(listOf(keptFunction, addedFunction), functionsState.functions) + assertEquals( + mapOf( + keptFunction.name to AppFunctionStatus(isEnabled = true), + addedFunction.name to AppFunctionStatus(isEnabled = true), + ), + functionsState.functionStatuses, + ) + assertEquals(mapOf(keptFunction.id to inputs), functionsState.functionInputs) + assertEquals(setOf(keptFunction.id), functionsState.expandedFunctions) + } + + @Test + fun `update without the selected app keeps its functions and statuses`() = + runTest { + val function = createFunction("test_function") + val otherAppPackage = + AppFunctionPackageMetadata( + packageName = "com.example.other", + components = AppFunctionComponentsMetadata(), + ) + val otherAppFunction = createFunction("other_function", otherAppPackage) + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns appFunctionsFlow + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(function))) + viewModel = createViewModel() + advanceUntilIdle() + viewModel.onAppSelected(testApp) + + // For example while the selected app is being reinstalled. + appFunctionsFlow.emit(mapOf(otherAppPackage to listOf(otherAppFunction))) + advanceUntilIdle() + + val functionsState = functionsFoundState() + assertEquals(listOf(function), functionsState.functions) + assertEquals( + mapOf(function.name to AppFunctionStatus(isEnabled = true)), + functionsState.functionStatuses, + ) + } + + @Test + fun `invokeFunction result keeps the statuses refreshed during the execution`() = + runTest { + val function = createFunction("test_function") + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns appFunctionsFlow + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(function))) + every { + mockConvertInputToAppFunctionDataUseCase(any(), any(), any()) + } returns Result.success(AppFunctionData.EMPTY) + val executionStarted = CompletableDeferred() + val pendingResult = CompletableDeferred() + coEvery { mockExecuteAppFunctionUseCase(any(), any(), any()) } coAnswers { + executionStarted.complete(Unit) + pendingResult.await() + } + viewModel = createViewModel() + advanceUntilIdle() + viewModel.onAppSelected(testApp) + + viewModel.invokeFunction(function) + // Inputs are converted on Dispatchers.Default, so wait for the execution to start. + executionStarted.await() + coEvery { mockGetAppFunctionStatesUseCase(any()) } returns + listOf(createState(function.name, isEnabled = false)) + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(function))) + advanceUntilIdle() + val result = ExecuteAppFunctionResult.Data(AppFunctionData.EMPTY, "{}") + pendingResult.complete(result) + advanceUntilIdle() + + val functionsState = functionsFoundState() + assertEquals(result, functionsState.executionResult) + assertEquals(function, functionsState.executedFunction) + assertEquals( + mapOf(function.name to AppFunctionStatus(isEnabled = false)), + functionsState.functionStatuses, ) } + + @Test + fun `invokeFunction shows input conversion error`() = + runTest { + val function = createFunction("test_function") + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns flowOf(mapOf(testAppPackage to listOf(function))) + every { + mockConvertInputToAppFunctionDataUseCase(any(), any(), any()) + } returns Result.failure(IllegalArgumentException("Invalid input")) + viewModel = createViewModel() + advanceUntilIdle() + viewModel.onAppSelected(testApp) + val inputs = mapOf("param1" to "value1") + viewModel.onFunctionInputsChange(function.id, inputs) + + viewModel.invokeFunction(function) + // Inputs are converted on Dispatchers.Default, so wait for the result. + val state = + viewModel.uiState.first { + (it.searchAppResultState as? SearchAppResultState.FunctionsFoundState) + ?.executionResult != null + } + + val functionsState = state.searchAppResultState as SearchAppResultState.FunctionsFoundState + val error = functionsState.executionResult as ExecuteAppFunctionResult.Error + assertEquals("Invalid input", error.exception.message) + assertEquals(function, functionsState.executedFunction) + assertEquals(inputs, functionsState.executedInputs) + } + + @Test + fun `onAppSelected shows activity-scoped function as dynamic and not runnable`() = + runTest { + val dynamicFunction = + createFunction("dynamic_function", scope = AppFunctionMetadata.SCOPE_ACTIVITY) + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns flowOf(mapOf(testAppPackage to listOf(dynamicFunction))) + viewModel = createViewModel() + advanceUntilIdle() + + viewModel.onAppSelected(testApp) + + val status = functionsFoundState().functionStatuses.getValue(dynamicFunction.name) + assertTrue(status.isDynamic) + assertFalse(status.canRun) + } + + @Test + fun `refresh after clearing the selected app keeps the idle state`() = + runTest { + val function = createFunction("test_function") + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns appFunctionsFlow + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(function))) + viewModel = createViewModel() + advanceUntilIdle() + viewModel.onAppSelected(testApp) + viewModel.onClearSelectedApp() + + appFunctionsFlow.emit(mapOf(testAppPackage to listOf(function))) + advanceUntilIdle() + + val state = viewModel.uiState.value + assertNull(state.selectedApp) + assertEquals(SearchAppResultState.Idle, state.searchAppResultState) + } + + @Test + fun `launchPendingIntent shows error on failure and clears it on success`() = + runTest { + val function = createFunction("test_function") + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns flowOf(mapOf(testAppPackage to listOf(function))) + val pendingIntent = mockk() + every { mockLaunchPendingIntentUseCase(pendingIntent) } returns + Result.failure(IllegalStateException("No activity found")) + viewModel = createViewModel() + advanceUntilIdle() + viewModel.onAppSelected(testApp) + + viewModel.launchPendingIntent(pendingIntent) + advanceUntilIdle() + + val error = functionsFoundState().executionResult as ExecuteAppFunctionResult.Error + assertEquals("No activity found", error.exception.message) + + every { mockLaunchPendingIntentUseCase(pendingIntent) } returns Result.success(Unit) + viewModel.launchPendingIntent(pendingIntent) + advanceUntilIdle() + + assertNull(functionsFoundState().executionResult) + } + + @Test + fun `onFunctionExpandedChange collapses an expanded function`() = + runTest { + val firstFunction = createFunction("first_function") + val secondFunction = createFunction("second_function") + every { + mockGetAppFunctionsUseCase(GetAppFunctionsParams(includeInternalTools = false)) + } returns flowOf(mapOf(testAppPackage to listOf(firstFunction, secondFunction))) + viewModel = createViewModel() + advanceUntilIdle() + viewModel.onAppSelected(testApp) + viewModel.onFunctionExpandedChange(firstFunction.id, expanded = true) + viewModel.onFunctionExpandedChange(secondFunction.id, expanded = true) + + viewModel.onFunctionExpandedChange(firstFunction.id, expanded = false) + + assertEquals(setOf(secondFunction.id), functionsFoundState().expandedFunctions) + } + + private fun createViewModel(): DebuggingViewModel = + DebuggingViewModel( + mockGetAppFunctionsUseCase, + mockGetAppFunctionStatesUseCase, + mockConvertInputToAppFunctionDataUseCase, + mockExecuteAppFunctionUseCase, + mockGetInstalledAppsUseCase, + mockTroubleshootAppUseCase, + mockLaunchPendingIntentUseCase, + mockSettingsRepository, + context, + ) + + private fun createFunction( + id: String, + packageMetadata: AppFunctionPackageMetadata = testAppPackage, + scope: Int = AppFunctionMetadata.SCOPE_GLOBAL, + ): AppFunctionMetadata = + AppFunctionMetadata( + name = AppFunctionName(packageMetadata.packageName, id), + schema = null, + parameters = emptyList(), + response = AppFunctionResponseMetadata(valueType = AppFunctionStringTypeMetadata(isNullable = false)), + packageMetadata = packageMetadata, + scope = scope, + ) + + private fun createState( + name: AppFunctionName, + isEnabled: Boolean, + ): AppFunctionState = + mockk().apply { + every { functionName } returns name + every { this@apply.isEnabled } returns isEnabled + } + + private fun functionsFoundState(): SearchAppResultState.FunctionsFoundState = + viewModel.uiState.value.searchAppResultState as SearchAppResultState.FunctionsFoundState + + private companion object { + const val TEST_PACKAGE_NAME = "com.example.app" + } }