diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/data/GeminiLiveProviderImpl.kt b/agent/app/src/main/java/com/example/appfunctions/agent/data/GeminiLiveProviderImpl.kt index 81ccc923..9e5f34d6 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/data/GeminiLiveProviderImpl.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/data/GeminiLiveProviderImpl.kt @@ -75,6 +75,8 @@ class GeminiLiveProviderImpl private val toolConverter: GeminiLiveToolConverter, private val webSocketConnector: suspend (wsUrl: String) -> WebSocketSession, ) : LiveLlmProvider { + override val liveModel: LlmModel = LlmModel(LlmProviderName.GEMINI, LIVE_MODEL_ID) + @Inject constructor( httpClient: HttpClient, @@ -653,7 +655,8 @@ class GeminiLiveProviderImpl companion object { private const val TAG = "GeminiLiveProvider" - const val LIVE_MODEL_NAME = "models/gemini-3.8-live" + const val LIVE_MODEL_ID = "gemini-3.8-live" + const val LIVE_MODEL_NAME = "models/$LIVE_MODEL_ID" const val DEFAULT_INPUT_SAMPLE_RATE_HZ = 16_000 const val DEFAULT_OUTPUT_SAMPLE_RATE_HZ = 24_000 private const val GEMINI_LIVE_WS_URL = diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/domain/LiveLlmProvider.kt b/agent/app/src/main/java/com/example/appfunctions/agent/domain/LiveLlmProvider.kt index 4c30de18..a7590270 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/domain/LiveLlmProvider.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/domain/LiveLlmProvider.kt @@ -16,12 +16,16 @@ package com.example.appfunctions.agent.domain import androidx.appfunctions.metadata.AppFunctionMetadata +import com.example.appfunctions.agent.data.LlmModel import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext /** Interface for LLM providers supporting bidirectional realtime audio and tool sessions. */ interface LiveLlmProvider { + /** The [LlmModel] identifier recorded on chat threads created for this live provider. */ + val liveModel: LlmModel + /** * Connects to the live LLM backend, completes session initialization with [tools] and optional * provider-specific [voiceName], and returns the active [LiveLlmSession]. The caller is diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreen.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreen.kt index f0ded4ce..e0d0f2a8 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreen.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreen.kt @@ -15,8 +15,15 @@ */ package com.example.appfunctions.agent.ui.screens.agentdemo +import android.Manifest +import android.content.ActivityNotFoundException +import android.content.Intent import android.content.pm.PackageManager import android.icu.text.ListFormatter +import android.provider.Settings +import androidx.activity.compose.LocalActivity +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandHorizontally import androidx.compose.animation.shrinkHorizontally @@ -49,8 +56,10 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Send import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material.icons.filled.GraphicEq import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Warning +import androidx.compose.material3.AlertDialog import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults @@ -63,6 +72,7 @@ import androidx.compose.material3.ExposedDropdownMenuAnchorType import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.ModalNavigationDrawer @@ -71,6 +81,7 @@ import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -110,6 +121,7 @@ import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.withStyle +import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize @@ -131,6 +143,9 @@ import com.example.appfunctions.agent.data.db.entities.ThreadEntity import com.example.appfunctions.agent.domain.AgentStatus import com.example.appfunctions.agent.domain.appfunction.AppInfo import com.example.appfunctions.agent.ui.screens.debugging.LazyExposedDropdownMenu +import com.example.appfunctions.agent.ui.screens.main.StatusWarningDialog +import com.example.appfunctions.agent.ui.theme.AppFunctionsAgentTheme +import com.example.appfunctions.agent.voice.AgentVoiceInteractionSession import com.mikepenz.markdown.m3.Markdown import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @@ -138,8 +153,61 @@ import kotlinx.coroutines.launch @Composable fun AgentDemoScreen(viewModel: AgentDemoViewModel = hiltViewModel()) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val activity = LocalActivity.current - AgentDemoContent(uiState = uiState, onEvent = viewModel::onEvent) + val audioPermissionLauncher = + rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission(), + ) { isGranted -> + viewModel.onEvent(AgentUiEvent.OnAudioPermissionResult(isGranted)) + } + + val assistantSettingsLauncher = + rememberLauncherForActivityResult( + contract = ActivityResultContracts.StartActivityForResult(), + ) { + viewModel.onEvent(AgentUiEvent.OnAssistantSettingsReturned) + } + + val liveSetupPrompt = (uiState as? AgentUiState.Loaded)?.liveSetupPrompt + LaunchedEffect(liveSetupPrompt, activity) { + when (liveSetupPrompt) { + is LiveSetupPrompt.RequestAudioPermission -> { + audioPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO) + } + is LiveSetupPrompt.LaunchAssistSession -> { + val isLaunched = + activity?.showAssist( + AgentVoiceInteractionSession.createSessionArgs( + threadId = liveSetupPrompt.threadId, + targetPackageName = liveSetupPrompt.targetPackageName, + ), + ) == true + viewModel.onEvent(AgentUiEvent.OnLiveSessionLaunchResult(isLaunched)) + } + else -> Unit + } + } + + val openAssistantSettings = { + try { + assistantSettingsLauncher.launch(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS)) + } catch (_: ActivityNotFoundException) { + try { + assistantSettingsLauncher.launch( + Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS), + ) + } catch (_: ActivityNotFoundException) { + viewModel.onEvent(AgentUiEvent.OnAssistantSettingsUnavailable) + } + } + } + + AgentDemoContent( + uiState = uiState, + onEvent = viewModel::onEvent, + onOpenAssistantSettings = openAssistantSettings, + ) } @OptIn(ExperimentalMaterial3Api::class) @@ -148,6 +216,7 @@ fun AgentDemoContent( uiState: AgentUiState, onEvent: (AgentUiEvent) -> Unit, initialSidePanelVisible: Boolean = false, + onOpenAssistantSettings: () -> Unit = {}, ) { val context = LocalContext.current val packageManager = context.packageManager @@ -177,6 +246,7 @@ fun AgentDemoContent( scope = scope, packageManager = packageManager, initialSidePanelVisible = initialSidePanelVisible, + onOpenAssistantSettings = onOpenAssistantSettings, ) } } @@ -210,6 +280,81 @@ fun AgentDemoContent( } } +@Composable +private fun LiveSetupPromptDialog( + prompt: LiveSetupPrompt?, + onOpenAssistantSettings: () -> Unit, + onDismiss: () -> Unit, +) { + when (prompt) { + null, + is LiveSetupPrompt.RequestAudioPermission, + is LiveSetupPrompt.LaunchAssistSession, + -> Unit + is LiveSetupPrompt.SelectDigitalAssistant -> { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.live_session_select_assistant_title)) }, + text = { Text(stringResource(R.string.live_session_select_assistant_prompt)) }, + confirmButton = { + TextButton(onClick = onOpenAssistantSettings) { + Text(stringResource(R.string.live_session_open_settings)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.live_session_cancel)) + } + }, + ) + } + LiveSetupPrompt.AudioPermissionDenied -> { + StatusWarningDialog( + title = stringResource(R.string.live_session_audio_permission_title), + message = stringResource(R.string.live_session_audio_permission_required), + isError = true, + onDismiss = onDismiss, + ) + } + LiveSetupPrompt.AssistantNotSelected -> { + StatusWarningDialog( + title = stringResource(R.string.live_session_select_assistant_title), + message = stringResource(R.string.live_session_assistant_not_selected), + isError = true, + onDismiss = onDismiss, + ) + } + LiveSetupPrompt.AssistantSettingsUnavailable -> { + StatusWarningDialog( + title = stringResource(R.string.live_session_select_assistant_title), + message = stringResource(R.string.live_session_assistant_settings_unavailable), + isError = true, + onDismiss = onDismiss, + ) + } + LiveSetupPrompt.AssistLaunchFailed -> { + StatusWarningDialog( + title = stringResource(R.string.live_session_launch_failed_title), + message = stringResource(R.string.live_session_launch_failed_message), + isError = true, + onDismiss = onDismiss, + ) + } + } +} + +@Preview(showBackground = true) +@Composable +private fun LiveSetupPromptDialogPreview() { + AppFunctionsAgentTheme { + LiveSetupPromptDialog( + prompt = LiveSetupPrompt.SelectDigitalAssistant(), + onOpenAssistantSettings = {}, + onDismiss = {}, + ) + } +} + @Composable fun AgentDemoLoadingScreen() { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { @@ -227,11 +372,23 @@ fun AgentDemoLoadedScreen( scope: CoroutineScope, packageManager: PackageManager, initialSidePanelVisible: Boolean = false, + onOpenAssistantSettings: () -> Unit = {}, ) { var messageText by remember { mutableStateOf(TextFieldValue("")) } var isSidePanelVisible by remember { mutableStateOf(initialSidePanelVisible) } var selectedAppPackageName by remember { mutableStateOf(null) } + LaunchedEffect(uiState.currentThread?.threadId) { + messageText = TextFieldValue("") + selectedAppPackageName = null + } + + LiveSetupPromptDialog( + prompt = uiState.liveSetupPrompt, + onOpenAssistantSettings = onOpenAssistantSettings, + onDismiss = { onEvent(AgentUiEvent.OnDismissLiveSetupPrompt) }, + ) + val chipBgColor = MaterialTheme.colorScheme.primaryContainer val chipTextColor = MaterialTheme.colorScheme.onPrimaryContainer val visualTransformation = @@ -254,6 +411,7 @@ fun AgentDemoLoadedScreen( .padding(horizontal = 8.dp), currentThread = uiState.currentThread, availableModels = uiState.availableModels, + isModelSelectionEnabled = !uiState.isCurrentThreadLive, onModelSelected = { onEvent(AgentUiEvent.OnModelSelected(it)) }, onMenuClick = { if (isWideScreen) { @@ -264,7 +422,10 @@ fun AgentDemoLoadedScreen( }, ) val defaultModel = - uiState.currentThread?.llmModel ?: uiState.availableModels.firstOrNull() + uiState.currentThread + ?.llmModel + ?.takeUnless { uiState.isCurrentThreadLive } + ?: uiState.availableModels.firstOrNull() IconButton( onClick = { if (defaultModel != null) { @@ -362,13 +523,21 @@ fun AgentDemoLoadedScreen( } } + val isLiveOnCurrentThread = uiState.liveStatus != null + val isTextInputEnabled = + uiState.currentThread != null && + !uiState.isCurrentThreadLive && + uiState.status == AgentStatus.Idle && + !isLiveOnCurrentThread + val isLiveStartEnabled = + uiState.currentThread != null && + uiState.status == AgentStatus.Idle && + !isLiveOnCurrentThread && + !uiState.isAnotherThreadLiveBusy + val sendMessage = { val textStr = messageText.text - if ( - uiState.currentThread != null && - textStr.isNotBlank() && - uiState.status == AgentStatus.Idle - ) { + if (isTextInputEnabled && textStr.isNotBlank()) { onEvent(AgentUiEvent.OnSendMessage(textStr, selectedAppPackageName)) messageText = TextFieldValue("") selectedAppPackageName = null @@ -456,10 +625,21 @@ fun AgentDemoLoadedScreen( false } }, - enabled = - uiState.currentThread != null && uiState.status == AgentStatus.Idle, + enabled = isTextInputEnabled, shape = CircleShape, - placeholder = { Text(stringResource(R.string.agent_demo_ask_agent)) }, + placeholder = { + Text( + stringResource( + when { + isLiveOnCurrentThread -> + R.string.agent_demo_live_active_placeholder + uiState.isCurrentThreadLive -> + R.string.agent_demo_live_thread_placeholder + else -> R.string.agent_demo_ask_agent + }, + ), + ) + }, visualTransformation = visualTransformation, colors = OutlinedTextFieldDefaults.colors( @@ -469,18 +649,40 @@ fun AgentDemoLoadedScreen( focusedBorderColor = Color.Transparent, ), trailingIcon = { - IconButton( - onClick = sendMessage, - enabled = - uiState.currentThread != null && - messageText.text.isNotBlank() && - uiState.status == AgentStatus.Idle, + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(end = 4.dp), ) { - Icon( - imageVector = Icons.AutoMirrored.Filled.Send, - contentDescription = - stringResource(R.string.agent_demo_send), - ) + IconButton( + onClick = { + onEvent( + AgentUiEvent.OnStartLiveSession( + selectedAppPackageName, + ), + ) + }, + enabled = isLiveStartEnabled, + colors = + IconButtonDefaults.iconButtonColors( + contentColor = MaterialTheme.colorScheme.primary, + ), + ) { + Icon( + imageVector = Icons.Default.GraphicEq, + contentDescription = + stringResource(R.string.agent_demo_live_start), + ) + } + IconButton( + onClick = sendMessage, + enabled = isTextInputEnabled && messageText.text.isNotBlank(), + ) { + Icon( + imageVector = Icons.AutoMirrored.Filled.Send, + contentDescription = + stringResource(R.string.agent_demo_send), + ) + } } }, ) @@ -555,6 +757,7 @@ fun ModelDropdown( modifier: Modifier = Modifier, currentThread: ThreadEntity?, availableModels: List = emptyList(), + isModelSelectionEnabled: Boolean = true, onModelSelected: (LlmModel) -> Unit, onMenuClick: () -> Unit, ) { @@ -565,8 +768,8 @@ fun ModelDropdown( } ExposedDropdownMenuBox( modifier = modifier, - expanded = expanded, - onExpandedChange = { expanded = !expanded }, + expanded = expanded && isModelSelectionEnabled, + onExpandedChange = { if (isModelSelectionEnabled) expanded = !expanded }, ) { Surface( modifier = Modifier.padding(bottom = 8.dp), @@ -602,7 +805,7 @@ fun ModelDropdown( .fillMaxHeight() .menuAnchor( ExposedDropdownMenuAnchorType.PrimaryEditable, - enabled = true, + enabled = isModelSelectionEnabled, ), verticalAlignment = Alignment.CenterVertically, ) { @@ -620,13 +823,15 @@ fun ModelDropdown( overflow = TextOverflow.Ellipsis, ) } - Icon(imageVector = Icons.Default.ArrowDropDown, contentDescription = null) + if (isModelSelectionEnabled) { + Icon(imageVector = Icons.Default.ArrowDropDown, contentDescription = null) + } } } } LazyExposedDropdownMenu( - expanded = expanded, + expanded = expanded && isModelSelectionEnabled, onDismissRequest = { expanded = false }, modifier = Modifier.exposedDropdownSize(), containerColor = MaterialTheme.colorScheme.surfaceBright, diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoViewModel.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoViewModel.kt index bdad5eb3..135afaf2 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoViewModel.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoViewModel.kt @@ -25,8 +25,10 @@ import com.example.appfunctions.agent.data.SettingsRepository import com.example.appfunctions.agent.data.db.entities.MessageProcessingStatus import com.example.appfunctions.agent.data.db.entities.MessageRole import com.example.appfunctions.agent.data.db.entities.ThreadEntity +import com.example.appfunctions.agent.domain.ActiveLiveSession import com.example.appfunctions.agent.domain.AgentOrchestrator import com.example.appfunctions.agent.domain.AgentStatus +import com.example.appfunctions.agent.domain.LiveAgentOrchestrator import com.example.appfunctions.agent.domain.LlmProviderFactory import com.example.appfunctions.agent.domain.appfunction.AppInfo import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionsParams @@ -35,6 +37,8 @@ import com.example.appfunctions.agent.domain.appfunction.GetInstalledAppsUseCase import com.example.appfunctions.agent.domain.chat.GetChatHistoryUseCase import com.example.appfunctions.agent.domain.chat.ManageThreadsUseCase import com.example.appfunctions.agent.domain.chat.SendMessageUseCase +import com.example.appfunctions.agent.domain.live.CheckAudioPermissionUseCase +import com.example.appfunctions.agent.domain.live.CheckVoiceServiceActiveUseCase import com.example.appfunctions.agent.domain.pendingintent.ConsumePendingIntentUseCase import com.example.appfunctions.agent.domain.pendingintent.LaunchPendingIntentUseCase import com.example.appfunctions.agent.domain.pendingintent.ObserveActivePendingIntentsUseCase @@ -60,6 +64,9 @@ class AgentDemoViewModel private val manageThreadsUseCase: ManageThreadsUseCase, private val sendMessageUseCase: SendMessageUseCase, private val agentOrchestrator: AgentOrchestrator, + private val liveAgentOrchestrator: LiveAgentOrchestrator, + private val checkAudioPermissionUseCase: CheckAudioPermissionUseCase, + private val checkVoiceServiceActiveUseCase: CheckVoiceServiceActiveUseCase, private val settingsRepository: SettingsRepository, private val llmProviderFactory: LlmProviderFactory, private val observeActivePendingIntentsUseCase: ObserveActivePendingIntentsUseCase, @@ -73,8 +80,10 @@ class AgentDemoViewModel private val installedApps = MutableStateFlow>(emptyList()) private val availableModels = MutableStateFlow>(emptyList()) + private val liveSetupPrompt = MutableStateFlow(null) private var observationJob: Job? = null + private var createLiveThreadJob: Job? = null init { viewModelScope.launch { @@ -124,50 +133,86 @@ class AgentDemoViewModel manageThreadsUseCase.getThreads(), settingsRepository.selectedProvider, agentOrchestrator.status, - ) { threads, provider, status -> - Triple(threads, provider, status) + liveAgentOrchestrator.activeSession, + ) { threads, provider, status, activeLiveSession -> + AgentStatusSnapshot(threads, provider, status, activeLiveSession) }, savedStateHandle.getStateFlow(MainActivity.ARG_THREAD_ID, null), installedApps, availableModels, + liveSetupPrompt, ) { - (threads, provider, status), + snapshot, targetThreadId, apps, models, + setupPrompt, -> - ThreadConfig(threads, provider, status, targetThreadId, apps, models) + ThreadConfig( + threads = snapshot.threads, + provider = snapshot.provider, + status = snapshot.status, + activeLiveSession = snapshot.activeLiveSession, + targetThreadId = targetThreadId, + installedApps = apps, + availableModels = models, + liveSetupPrompt = setupPrompt, + ) } - .collectLatest { (threads, _, status, targetThreadId, apps, models) -> + .collectLatest { config -> val currentThread = - threads.find { it.threadId == targetThreadId } ?: threads.firstOrNull() + config.threads.find { it.threadId == config.targetThreadId } + ?: config.threads.firstOrNull() val previousThreadId = (_uiState.value as? AgentUiState.Loaded)?.currentThread?.threadId + val activeLiveSession = config.activeLiveSession + val liveStatusForCurrentThread = + if ( + currentThread != null && + activeLiveSession?.threadId == currentThread.threadId + ) { + activeLiveSession.status + } else { + null + } + val isAnotherThreadLiveBusy = + activeLiveSession != null && + activeLiveSession.threadId != currentThread?.threadId + val currentLoadedState = _uiState.value as? AgentUiState.Loaded + val isCurrentThreadLive = + currentThread != null && + currentThread.llmModel == + llmProviderFactory + .getLiveProvider(currentThread.llmModel.providerName) + .liveModel _uiState.value = AgentUiState.Loaded( currentThread = currentThread, + isCurrentThreadLive = isCurrentThreadLive, messages = - if (currentThread != null) { + if (currentThread != null && currentThread.threadId == previousThreadId) { currentLoadedState?.messages ?: emptyList() } else { emptyList() }, - status = status, - threads = threads, + status = config.status, + liveStatus = liveStatusForCurrentThread, + isAnotherThreadLiveBusy = isAnotherThreadLiveBusy, + liveSetupPrompt = config.liveSetupPrompt, + threads = config.threads, activePendingActionIds = currentLoadedState?.activePendingActionIds ?: emptySet(), - installedApps = apps, - availableModels = models, + installedApps = config.installedApps, + availableModels = config.availableModels, ) if (currentThread == null) { observationJob?.cancel() observationJob = null } else if (observationJob == null || previousThreadId != currentThread.threadId) { - // Start observing messages for the current thread if not already doing so observationJob?.cancel() observationJob = viewModelScope.launch { @@ -196,7 +241,10 @@ class AgentDemoViewModel val currentState = _uiState.value when (event) { is AgentUiEvent.OnSendMessage -> { - val currentThread = (currentState as? AgentUiState.Loaded)?.currentThread + val currentThread = + (currentState as? AgentUiState.Loaded) + ?.takeUnless { it.isCurrentThreadLive } + ?.currentThread if (currentThread != null) { viewModelScope.launch { sendMessageUseCase( @@ -213,7 +261,7 @@ class AgentDemoViewModel if (currentState is AgentUiState.Loaded) { viewModelScope.launch { val currentThread = currentState.currentThread - if (currentThread != null) { + if (currentThread != null && !currentState.isCurrentThreadLive) { manageThreadsUseCase.updateThreadModel( currentThread.threadId, event.model, @@ -236,20 +284,140 @@ class AgentDemoViewModel launchPendingIntentUseCase(pendingIntent) } } + is AgentUiEvent.OnStartLiveSession -> { + tryStartLiveSession(event.targetPackageName) + } + is AgentUiEvent.OnLiveSessionLaunchResult -> { + val pendingThreadId = + savedStateHandle.get(KEY_PENDING_LAUNCH_THREAD_ID) + val previousThreadId = + savedStateHandle.get(KEY_PREVIOUS_THREAD_ID) + clearPendingLaunchThread() + if (event.isLaunched) { + liveSetupPrompt.value = null + } else { + savedStateHandle[MainActivity.ARG_THREAD_ID] = previousThreadId + if (pendingThreadId != null) { + viewModelScope.launch { + manageThreadsUseCase.deleteThread(pendingThreadId) + } + } + liveSetupPrompt.value = LiveSetupPrompt.AssistLaunchFailed + } + } + is AgentUiEvent.OnAudioPermissionResult -> { + val pendingTarget = + savedStateHandle.get(KEY_PENDING_LIVE_TARGET_PACKAGE) + if (event.isGranted) { + liveSetupPrompt.value = null + tryStartLiveSession(pendingTarget) + } else { + clearPendingLiveTarget() + liveSetupPrompt.value = LiveSetupPrompt.AudioPermissionDenied + } + } + AgentUiEvent.OnAssistantSettingsReturned -> { + val pendingTarget = + savedStateHandle.get(KEY_PENDING_LIVE_TARGET_PACKAGE) + clearPendingLiveTarget() + if (checkVoiceServiceActiveUseCase()) { + launchNewLiveSession(pendingTarget) + } else { + liveSetupPrompt.value = LiveSetupPrompt.AssistantNotSelected + } + } + AgentUiEvent.OnAssistantSettingsUnavailable -> { + clearPendingLiveTarget() + liveSetupPrompt.value = LiveSetupPrompt.AssistantSettingsUnavailable + } + AgentUiEvent.OnDismissLiveSetupPrompt -> { + clearPendingLiveTarget() + liveSetupPrompt.value = null + } + } + } + + private fun tryStartLiveSession(targetPackageName: String?) { + if ( + liveAgentOrchestrator.activeSession.value != null || + agentOrchestrator.status.value != AgentStatus.Idle + ) { + return } + if (!checkAudioPermissionUseCase()) { + savedStateHandle[KEY_PENDING_LIVE_TARGET_PACKAGE] = targetPackageName + liveSetupPrompt.value = LiveSetupPrompt.RequestAudioPermission(targetPackageName) + return + } + if (!checkVoiceServiceActiveUseCase()) { + savedStateHandle[KEY_PENDING_LIVE_TARGET_PACKAGE] = targetPackageName + liveSetupPrompt.value = LiveSetupPrompt.SelectDigitalAssistant(targetPackageName) + return + } + clearPendingLiveTarget() + launchNewLiveSession(targetPackageName) + } + + private fun launchNewLiveSession(targetPackageName: String?) { + if ( + createLiveThreadJob?.isActive == true || + savedStateHandle.get(KEY_PENDING_LAUNCH_THREAD_ID) != null + ) { + return + } + createLiveThreadJob = + viewModelScope.launch { + val previousThreadId = + (_uiState.value as? AgentUiState.Loaded)?.currentThread?.threadId + val selectedProvider = settingsRepository.selectedProvider.first() + val liveModel = llmProviderFactory.getLiveProvider(selectedProvider).liveModel + val liveThreadId = manageThreadsUseCase.createThread(liveModel) + savedStateHandle[KEY_PENDING_LAUNCH_THREAD_ID] = liveThreadId + savedStateHandle[KEY_PREVIOUS_THREAD_ID] = previousThreadId + savedStateHandle[MainActivity.ARG_THREAD_ID] = liveThreadId + liveSetupPrompt.value = + LiveSetupPrompt.LaunchAssistSession( + threadId = liveThreadId, + targetPackageName = targetPackageName, + ) + } + } + + private fun clearPendingLiveTarget() { + savedStateHandle.remove(KEY_PENDING_LIVE_TARGET_PACKAGE) + } + + private fun clearPendingLaunchThread() { + savedStateHandle.remove(KEY_PENDING_LAUNCH_THREAD_ID) + savedStateHandle.remove(KEY_PREVIOUS_THREAD_ID) } private suspend fun createAndSelectThread(llmModel: LlmModel) { val threadId = manageThreadsUseCase.createThread(llmModel) savedStateHandle[MainActivity.ARG_THREAD_ID] = threadId } + + private companion object { + const val KEY_PENDING_LIVE_TARGET_PACKAGE = "pending_live_target_package" + const val KEY_PENDING_LAUNCH_THREAD_ID = "pending_launch_live_thread_id" + const val KEY_PREVIOUS_THREAD_ID = "previous_thread_id_before_live" + } } +private data class AgentStatusSnapshot( + val threads: List, + val provider: LlmProviderName, + val status: AgentStatus, + val activeLiveSession: ActiveLiveSession?, +) + private data class ThreadConfig( val threads: List, val provider: LlmProviderName, val status: AgentStatus, + val activeLiveSession: ActiveLiveSession?, val targetThreadId: String?, val installedApps: List, val availableModels: List, + val liveSetupPrompt: LiveSetupPrompt?, ) diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentUiState.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentUiState.kt index bd92f973..a393f77a 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentUiState.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentUiState.kt @@ -19,6 +19,7 @@ import com.example.appfunctions.agent.data.LlmModel import com.example.appfunctions.agent.data.db.entities.MessageEntity import com.example.appfunctions.agent.data.db.entities.ThreadEntity import com.example.appfunctions.agent.domain.AgentStatus +import com.example.appfunctions.agent.domain.LiveAgentStatus import com.example.appfunctions.agent.domain.appfunction.AppInfo /** Represents the UI state for the Agent Demo screen. */ @@ -27,8 +28,12 @@ sealed class AgentUiState { data class Loaded( val currentThread: ThreadEntity? = null, + val isCurrentThreadLive: Boolean = false, val messages: List = emptyList(), val status: AgentStatus = AgentStatus.Idle, + val liveStatus: LiveAgentStatus? = null, + val isAnotherThreadLiveBusy: Boolean = false, + val liveSetupPrompt: LiveSetupPrompt? = null, val threads: List = emptyList(), val activePendingActionIds: Set = emptySet(), val installedApps: List = emptyList(), @@ -36,6 +41,26 @@ sealed class AgentUiState { ) : AgentUiState() } +/** Setup prompt or launch request emitted when starting a Live voice session. */ +sealed class LiveSetupPrompt { + data class RequestAudioPermission(val targetPackageName: String? = null) : LiveSetupPrompt() + + data class SelectDigitalAssistant(val targetPackageName: String? = null) : LiveSetupPrompt() + + data class LaunchAssistSession( + val threadId: String, + val targetPackageName: String? = null, + ) : LiveSetupPrompt() + + data object AudioPermissionDenied : LiveSetupPrompt() + + data object AssistantNotSelected : LiveSetupPrompt() + + data object AssistantSettingsUnavailable : LiveSetupPrompt() + + data object AssistLaunchFailed : LiveSetupPrompt() +} + /** Represents UI events for the Agent Demo screen. */ sealed class AgentUiEvent { data class OnSendMessage( @@ -50,4 +75,16 @@ sealed class AgentUiEvent { data class OnThreadSelected(val threadId: String) : AgentUiEvent() data class OnConfirmAction(val pendingIntentId: String) : AgentUiEvent() + + data class OnStartLiveSession(val targetPackageName: String? = null) : AgentUiEvent() + + data class OnLiveSessionLaunchResult(val isLaunched: Boolean) : AgentUiEvent() + + data class OnAudioPermissionResult(val isGranted: Boolean) : AgentUiEvent() + + data object OnAssistantSettingsReturned : AgentUiEvent() + + data object OnAssistantSettingsUnavailable : AgentUiEvent() + + data object OnDismissLiveSetupPrompt : AgentUiEvent() } diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveOverlayUiState.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveOverlayUiState.kt index 4d9d21d7..fe8364d1 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveOverlayUiState.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveOverlayUiState.kt @@ -40,8 +40,6 @@ sealed interface LiveOverlayStatus { sealed interface Error : LiveOverlayStatus { data object AudioPermissionRequired : Error - data class NoModelAvailable(val providerDisplayName: String) : Error - data class SessionFailed(val message: String) : Error } } diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveVoiceOverlayStateHolder.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveVoiceOverlayStateHolder.kt index c83429a9..277a0541 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveVoiceOverlayStateHolder.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveVoiceOverlayStateHolder.kt @@ -226,10 +226,7 @@ class LiveVoiceOverlayStateHolder return@launch } - val resolvedThreadId = - requestedThreadId - ?: resolveOrCreateDefaultThreadId(requestedTargetPackageName) - ?: return@launch + val resolvedThreadId = requestedThreadId ?: createLiveThreadId() localSessionState.value = LocalOverlaySessionState.Running( @@ -269,29 +266,10 @@ class LiveVoiceOverlayStateHolder } } - private suspend fun resolveOrCreateDefaultThreadId(requestedTargetPackageName: String?): String? { - val existingThread = manageThreadsUseCase.getThreads().first().firstOrNull() - if (existingThread != null) { - return existingThread.threadId - } - + private suspend fun createLiveThreadId(): String { val selectedProvider = settingsRepository.selectedProvider.first() - val apiKey = settingsRepository.getApiKey(selectedProvider).first() - val defaultModel = - llmProviderFactory - .getProvider(selectedProvider) - .getAvailableModels(apiKey) - .firstOrNull() - if (defaultModel == null) { - localSessionState.value = - LocalOverlaySessionState.Failed( - threadId = null, - targetPackageName = requestedTargetPackageName, - error = LiveOverlayStatus.Error.NoModelAvailable(selectedProvider.displayName), - ) - return null - } - return manageThreadsUseCase.createThread(defaultModel) + val liveModel = llmProviderFactory.getLiveProvider(selectedProvider).liveModel + return manageThreadsUseCase.createThread(liveModel) } override fun close() { diff --git a/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveVoiceSessionOverlay.kt b/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveVoiceSessionOverlay.kt index fb9202ba..57a3c121 100644 --- a/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveVoiceSessionOverlay.kt +++ b/agent/app/src/main/java/com/example/appfunctions/agent/ui/voice/LiveVoiceSessionOverlay.kt @@ -145,11 +145,6 @@ fun LiveVoiceSessionOverlay( } LiveOverlayStatus.Error.AudioPermissionRequired -> stringResource(R.string.live_session_audio_permission_required) - is LiveOverlayStatus.Error.NoModelAvailable -> - stringResource( - R.string.live_session_no_model_available, - status.providerDisplayName, - ) is LiveOverlayStatus.Error.SessionFailed -> status.message } val subtitleColor = diff --git a/agent/app/src/main/res/values/strings.xml b/agent/app/src/main/res/values/strings.xml index da0f46fb..71e3d6e1 100644 --- a/agent/app/src/main/res/values/strings.xml +++ b/agent/app/src/main/res/values/strings.xml @@ -122,15 +122,26 @@ Yes, go ahead Done I can perform this action for you. Should I proceed? + Start Live Voice Session End Live Voice Session + Live voice session active… + Live voice transcript Connecting… Listening… Live Agent Using %1$s… AppFunction Retry + Microphone Permission Required Microphone permission is required for Live voice sessions. - No model available for %1$s. Check your API key in Settings. + Select Digital Assistant + Select AppFunction Testing Agent as your Digital Assistant to start a Live voice session. + AppFunction Testing Agent was not selected as your Digital Assistant. Select it in Settings to start a Live voice session. + Open Settings + Cancel + Digital Assistant settings are not available on this device. + Unable to Start Live Session + Could not open the Digital Assistant overlay. Ensure this app is selected as your Digital Assistant and try again. Copied value of %1$s Copy value diff --git a/agent/app/src/screenshotTest/kotlin/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTest.kt b/agent/app/src/screenshotTest/kotlin/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTest.kt index 2aeb5c9e..e382f063 100644 --- a/agent/app/src/screenshotTest/kotlin/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTest.kt +++ b/agent/app/src/screenshotTest/kotlin/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTest.kt @@ -25,9 +25,11 @@ import com.example.appfunctions.agent.data.db.entities.MessageProcessingStatus import com.example.appfunctions.agent.data.db.entities.MessageRole import com.example.appfunctions.agent.data.db.entities.ThreadEntity import com.example.appfunctions.agent.domain.AgentStatus +import com.example.appfunctions.agent.domain.LiveAgentStatus private val previewFlashModel = LlmModel(LlmProviderName.GEMINI, "gemini-3-flash-preview") private val previewProModel = LlmModel(LlmProviderName.GEMINI, "gemini-3.1-pro-preview") +private val previewLiveModel = LlmModel(LlmProviderName.GEMINI, "gemini-3.8-live") /** Screenshot test for [AgentDemoScreen]. */ @PreviewTest @@ -352,3 +354,60 @@ fun AgentDemoScreenSidePanelPreview() { initialSidePanelVisible = true, ) } + +@PreviewTest +@Preview(showBackground = true) +@Composable +fun AgentDemoScreenLiveActivePreview() { + val thread = + ThreadEntity("thread-live", System.currentTimeMillis(), previewLiveModel, null) + AgentDemoContent( + uiState = + AgentUiState.Loaded( + messages = emptyList(), + status = AgentStatus.Idle, + liveStatus = LiveAgentStatus.Listening, + currentThread = thread, + isCurrentThreadLive = true, + ), + onEvent = {}, + ) +} + +@PreviewTest +@Preview(showBackground = true) +@Composable +fun AgentDemoScreenLiveTranscriptPreview() { + val thread = + ThreadEntity("thread-live", System.currentTimeMillis(), previewLiveModel, null) + val messages = + listOf( + MessageEntity( + "1", + "thread-live", + MessageRole.USER, + "Check my unread messages", + System.currentTimeMillis(), + MessageProcessingStatus.PROCESSED, + ), + MessageEntity( + "2", + "thread-live", + MessageRole.ASSISTANT, + "You have one unread message from Alice.", + System.currentTimeMillis(), + MessageProcessingStatus.PROCESSED, + ), + ) + AgentDemoContent( + uiState = + AgentUiState.Loaded( + messages = messages, + status = AgentStatus.Idle, + liveStatus = null, + currentThread = thread, + isCurrentThreadLive = true, + ), + onEvent = {}, + ) +} diff --git a/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveActivePreview_748aa731_0.png b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveActivePreview_748aa731_0.png new file mode 100644 index 00000000..9db0fe69 Binary files /dev/null and b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveActivePreview_748aa731_0.png differ diff --git a/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveTranscriptPreview_748aa731_0.png b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveTranscriptPreview_748aa731_0.png new file mode 100644 index 00000000..f6458b3e Binary files /dev/null and b/agent/app/src/screenshotTestRetailDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveTranscriptPreview_748aa731_0.png differ diff --git a/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveActivePreview_748aa731_0.png b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveActivePreview_748aa731_0.png new file mode 100644 index 00000000..9db0fe69 Binary files /dev/null and b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveActivePreview_748aa731_0.png differ diff --git a/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveTranscriptPreview_748aa731_0.png b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveTranscriptPreview_748aa731_0.png new file mode 100644 index 00000000..f6458b3e Binary files /dev/null and b/agent/app/src/screenshotTestStandardDebug/reference/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoScreenScreenshotTestKt/AgentDemoScreenLiveTranscriptPreview_748aa731_0.png differ diff --git a/agent/app/src/test/java/com/example/appfunctions/agent/data/GeminiLiveProviderImplTest.kt b/agent/app/src/test/java/com/example/appfunctions/agent/data/GeminiLiveProviderImplTest.kt index 10e78b47..2817db04 100644 --- a/agent/app/src/test/java/com/example/appfunctions/agent/data/GeminiLiveProviderImplTest.kt +++ b/agent/app/src/test/java/com/example/appfunctions/agent/data/GeminiLiveProviderImplTest.kt @@ -760,6 +760,15 @@ class GeminiLiveProviderImplTest { ) } + @Test + fun `liveModel exposes Gemini Live model identifier`() { + val provider = createProvider { error("Not expected to connect") } + assertEquals( + LlmModel(LlmProviderName.GEMINI, GeminiLiveProviderImpl.LIVE_MODEL_ID), + provider.liveModel, + ) + } + private suspend fun CoroutineScope.collectSingleServerFrame( frameJson: String, tools: List = emptyList(), diff --git a/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoViewModelTest.kt b/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoViewModelTest.kt index 6e02f462..604bdc1a 100644 --- a/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoViewModelTest.kt +++ b/agent/app/src/test/java/com/example/appfunctions/agent/ui/screens/agentdemo/AgentDemoViewModelTest.kt @@ -24,8 +24,12 @@ import com.example.appfunctions.agent.data.db.entities.MessageEntity import com.example.appfunctions.agent.data.db.entities.MessageProcessingStatus import com.example.appfunctions.agent.data.db.entities.MessageRole import com.example.appfunctions.agent.data.db.entities.ThreadEntity +import com.example.appfunctions.agent.domain.ActiveLiveSession import com.example.appfunctions.agent.domain.AgentOrchestrator import com.example.appfunctions.agent.domain.AgentStatus +import com.example.appfunctions.agent.domain.LiveAgentOrchestrator +import com.example.appfunctions.agent.domain.LiveAgentStatus +import com.example.appfunctions.agent.domain.LiveLlmProvider import com.example.appfunctions.agent.domain.LlmProvider import com.example.appfunctions.agent.domain.LlmProviderFactory import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionsParams @@ -34,6 +38,8 @@ import com.example.appfunctions.agent.domain.appfunction.GetInstalledAppsUseCase import com.example.appfunctions.agent.domain.chat.GetChatHistoryUseCase import com.example.appfunctions.agent.domain.chat.ManageThreadsUseCase import com.example.appfunctions.agent.domain.chat.SendMessageUseCase +import com.example.appfunctions.agent.domain.live.CheckAudioPermissionUseCase +import com.example.appfunctions.agent.domain.live.CheckVoiceServiceActiveUseCase import com.example.appfunctions.agent.domain.pendingintent.ConsumePendingIntentUseCase import com.example.appfunctions.agent.domain.pendingintent.LaunchPendingIntentUseCase import com.example.appfunctions.agent.domain.pendingintent.ObserveActivePendingIntentsUseCase @@ -51,6 +57,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 @@ -63,9 +72,13 @@ class AgentDemoViewModelTest { private lateinit var manageThreadsUseCase: ManageThreadsUseCase private lateinit var sendMessageUseCase: SendMessageUseCase private lateinit var agentOrchestrator: AgentOrchestrator + private lateinit var liveAgentOrchestrator: LiveAgentOrchestrator + private lateinit var checkAudioPermissionUseCase: CheckAudioPermissionUseCase + private lateinit var checkVoiceServiceActiveUseCase: CheckVoiceServiceActiveUseCase private lateinit var settingsRepository: SettingsRepository private lateinit var llmProviderFactory: LlmProviderFactory private lateinit var llmProvider: LlmProvider + private lateinit var liveLlmProvider: LiveLlmProvider private lateinit var savedStateHandle: SavedStateHandle private lateinit var observeActivePendingIntentsUseCase: ObserveActivePendingIntentsUseCase private lateinit var launchPendingIntentUseCase: LaunchPendingIntentUseCase @@ -77,11 +90,13 @@ class AgentDemoViewModelTest { private val testModelFlash = LlmModel(LlmProviderName.GEMINI, "gemini-2.5-flash") private val testModelPro = LlmModel(LlmProviderName.GEMINI, "gemini-2.5-pro") + private val testModelLive = LlmModel(LlmProviderName.GEMINI, "gemini-3.8-live") private val threadsFlow = MutableStateFlow>(emptyList()) private val selectedProviderFlow = MutableStateFlow(LlmProviderName.GEMINI) private val geminiApiKeyFlow = MutableStateFlow(null) private val agentStatusFlow = MutableStateFlow(AgentStatus.Idle) + private val activeLiveSessionFlow = MutableStateFlow(null) private val messagesFlow = MutableStateFlow>(emptyList()) private val activePendingActionIdsFlow = MutableStateFlow>(emptySet()) @@ -93,9 +108,13 @@ class AgentDemoViewModelTest { manageThreadsUseCase = mockk() sendMessageUseCase = mockk() agentOrchestrator = mockk() + liveAgentOrchestrator = mockk(relaxed = true) + checkAudioPermissionUseCase = mockk() + checkVoiceServiceActiveUseCase = mockk() settingsRepository = mockk() llmProviderFactory = mockk() llmProvider = mockk() + liveLlmProvider = mockk() savedStateHandle = SavedStateHandle() observeActivePendingIntentsUseCase = mockk() launchPendingIntentUseCase = mockk() @@ -113,7 +132,12 @@ class AgentDemoViewModelTest { every { settingsRepository.geminiApiKey } returns geminiApiKeyFlow every { llmProviderFactory.getProvider(any()) } returns llmProvider coEvery { llmProvider.getAvailableModels(any()) } returns listOf(testModelFlash, testModelPro) + every { llmProviderFactory.getLiveProvider(any()) } returns liveLlmProvider + every { liveLlmProvider.liveModel } returns testModelLive every { agentOrchestrator.status } returns agentStatusFlow + every { liveAgentOrchestrator.activeSession } returns activeLiveSessionFlow + every { checkAudioPermissionUseCase() } returns true + every { checkVoiceServiceActiveUseCase() } returns true every { getChatHistoryUseCase(any()) } returns messagesFlow every { observeActivePendingIntentsUseCase() } returns activePendingActionIdsFlow @@ -133,6 +157,9 @@ class AgentDemoViewModelTest { manageThreadsUseCase, sendMessageUseCase, agentOrchestrator, + liveAgentOrchestrator, + checkAudioPermissionUseCase, + checkVoiceServiceActiveUseCase, settingsRepository, llmProviderFactory, observeActivePendingIntentsUseCase, @@ -317,4 +344,183 @@ class AgentDemoViewModelTest { assertEquals(null, loadedState.currentThread) assertEquals(emptyList(), loadedState.availableModels) } + + @Test + fun `uiState reflects LiveAgentOrchestrator activeSession on current and other threads`() = + runTest { + val thread1 = ThreadEntity("thread-1", 2000L, testModelFlash, null) + val thread2 = ThreadEntity("thread-2", 1000L, testModelFlash, null) + threadsFlow.value = listOf(thread1, thread2) + + viewModel = createViewModel() + + activeLiveSessionFlow.value = + ActiveLiveSession( + threadId = "thread-1", + status = LiveAgentStatus.Listening, + ) + + val stateOnThread1 = viewModel.uiState.value as AgentUiState.Loaded + assertEquals(LiveAgentStatus.Listening, stateOnThread1.liveStatus) + assertFalse(stateOnThread1.isAnotherThreadLiveBusy) + + viewModel.onEvent(AgentUiEvent.OnThreadSelected("thread-2")) + + val stateOnThread2 = viewModel.uiState.value as AgentUiState.Loaded + assertNull(stateOnThread2.liveStatus) + assertTrue(stateOnThread2.isAnotherThreadLiveBusy) + } + + @Test + fun `OnStartLiveSession checks permission and assistant role before creating Live thread and emitting LaunchAssistSession`() = + runTest { + val thread1 = ThreadEntity("thread-1", 2000L, testModelFlash, null) + threadsFlow.value = listOf(thread1) + every { checkAudioPermissionUseCase() } returns false + every { checkVoiceServiceActiveUseCase() } returns false + coEvery { manageThreadsUseCase.createThread(testModelLive) } coAnswers { + val liveThread = ThreadEntity("thread-live", 3000L, testModelLive, null) + threadsFlow.value = listOf(liveThread) + threadsFlow.value + "thread-live" + } + + viewModel = createViewModel() + + viewModel.onEvent(AgentUiEvent.OnStartLiveSession("com.example.chat")) + assertEquals( + LiveSetupPrompt.RequestAudioPermission("com.example.chat"), + (viewModel.uiState.value as AgentUiState.Loaded).liveSetupPrompt, + ) + + every { checkAudioPermissionUseCase() } returns true + viewModel.onEvent(AgentUiEvent.OnAudioPermissionResult(isGranted = true)) + assertEquals( + LiveSetupPrompt.SelectDigitalAssistant("com.example.chat"), + (viewModel.uiState.value as AgentUiState.Loaded).liveSetupPrompt, + ) + + every { checkVoiceServiceActiveUseCase() } returns true + viewModel.onEvent(AgentUiEvent.OnAssistantSettingsReturned) + val afterAssistantReady = viewModel.uiState.value as AgentUiState.Loaded + coVerify(exactly = 1) { manageThreadsUseCase.createThread(testModelLive) } + assertEquals("thread-live", afterAssistantReady.currentThread?.threadId) + assertTrue(afterAssistantReady.isCurrentThreadLive) + assertEquals( + LiveSetupPrompt.LaunchAssistSession("thread-live", "com.example.chat"), + afterAssistantReady.liveSetupPrompt, + ) + + viewModel.onEvent(AgentUiEvent.OnLiveSessionLaunchResult(isLaunched = true)) + val afterLaunched = viewModel.uiState.value as AgentUiState.Loaded + assertNull(afterLaunched.liveSetupPrompt) + assertEquals("thread-live", afterLaunched.currentThread?.threadId) + } + + @Test + fun `OnAssistantSettingsReturned surfaces AssistantNotSelected when voice service is still inactive`() = + runTest { + val thread1 = ThreadEntity("thread-1", 2000L, testModelFlash, null) + threadsFlow.value = listOf(thread1) + every { checkAudioPermissionUseCase() } returns true + every { checkVoiceServiceActiveUseCase() } returns false + + viewModel = createViewModel() + + viewModel.onEvent(AgentUiEvent.OnStartLiveSession("com.example.chat")) + assertEquals( + LiveSetupPrompt.SelectDigitalAssistant("com.example.chat"), + (viewModel.uiState.value as AgentUiState.Loaded).liveSetupPrompt, + ) + + viewModel.onEvent(AgentUiEvent.OnAssistantSettingsReturned) + val afterReturned = viewModel.uiState.value as AgentUiState.Loaded + assertEquals(LiveSetupPrompt.AssistantNotSelected, afterReturned.liveSetupPrompt) + assertEquals("thread-1", afterReturned.currentThread?.threadId) + coVerify(exactly = 0) { manageThreadsUseCase.createThread(any()) } + } + + @Test + fun `OnLiveSessionLaunchResult failure deletes pending Live thread and restores previous thread`() = + runTest { + val thread1 = ThreadEntity("thread-1", 2000L, testModelFlash, null) + threadsFlow.value = listOf(thread1) + coEvery { manageThreadsUseCase.createThread(testModelLive) } coAnswers { + val liveThread = ThreadEntity("thread-live", 3000L, testModelLive, null) + threadsFlow.value = listOf(liveThread) + threadsFlow.value + "thread-live" + } + coEvery { manageThreadsUseCase.deleteThread("thread-live") } coAnswers { + threadsFlow.value = threadsFlow.value.filterNot { it.threadId == "thread-live" } + } + + viewModel = createViewModel() + + viewModel.onEvent(AgentUiEvent.OnStartLiveSession()) + assertEquals( + "thread-live", + (viewModel.uiState.value as AgentUiState.Loaded).currentThread?.threadId, + ) + + viewModel.onEvent(AgentUiEvent.OnLiveSessionLaunchResult(isLaunched = false)) + val afterFailure = viewModel.uiState.value as AgentUiState.Loaded + coVerify(exactly = 1) { manageThreadsUseCase.deleteThread("thread-live") } + assertEquals("thread-1", afterFailure.currentThread?.threadId) + assertEquals(LiveSetupPrompt.AssistLaunchFailed, afterFailure.liveSetupPrompt) + } + + @Test + fun `Live-model thread ignores OnSendMessage and OnModelSelected creates new text thread`() = + runTest { + val liveThread = ThreadEntity("thread-live", 3000L, testModelLive, null) + threadsFlow.value = listOf(liveThread) + coEvery { manageThreadsUseCase.createThread(testModelPro) } coAnswers { + val newTextThread = ThreadEntity("thread-text", 4000L, testModelPro, null) + threadsFlow.value = listOf(newTextThread, liveThread) + "thread-text" + } + + viewModel = createViewModel() + assertTrue((viewModel.uiState.value as AgentUiState.Loaded).isCurrentThreadLive) + + viewModel.onEvent(AgentUiEvent.OnSendMessage("Should be ignored")) + coVerify(exactly = 0) { + sendMessageUseCase(any(), any(), any(), any(), any(), any(), any()) + } + + viewModel.onEvent(AgentUiEvent.OnModelSelected(testModelPro)) + coVerify(exactly = 0) { manageThreadsUseCase.updateThreadModel(any(), any()) } + coVerify(exactly = 1) { manageThreadsUseCase.createThread(testModelPro) } + val afterModelSelected = viewModel.uiState.value as AgentUiState.Loaded + assertEquals("thread-text", afterModelSelected.currentThread?.threadId) + assertFalse(afterModelSelected.isCurrentThreadLive) + } + + @Test + fun `Live setup failure events surface error prompts and dismiss clears prompt`() = + runTest { + val thread1 = ThreadEntity("thread-1", 2000L, testModelFlash, null) + threadsFlow.value = listOf(thread1) + viewModel = createViewModel() + + viewModel.onEvent(AgentUiEvent.OnAudioPermissionResult(isGranted = false)) + assertEquals( + LiveSetupPrompt.AudioPermissionDenied, + (viewModel.uiState.value as AgentUiState.Loaded).liveSetupPrompt, + ) + + viewModel.onEvent(AgentUiEvent.OnAssistantSettingsUnavailable) + assertEquals( + LiveSetupPrompt.AssistantSettingsUnavailable, + (viewModel.uiState.value as AgentUiState.Loaded).liveSetupPrompt, + ) + + viewModel.onEvent(AgentUiEvent.OnLiveSessionLaunchResult(isLaunched = false)) + assertEquals( + LiveSetupPrompt.AssistLaunchFailed, + (viewModel.uiState.value as AgentUiState.Loaded).liveSetupPrompt, + ) + + viewModel.onEvent(AgentUiEvent.OnDismissLiveSetupPrompt) + assertNull((viewModel.uiState.value as AgentUiState.Loaded).liveSetupPrompt) + } } diff --git a/agent/app/src/test/java/com/example/appfunctions/agent/ui/voice/LiveVoiceOverlayStateHolderTest.kt b/agent/app/src/test/java/com/example/appfunctions/agent/ui/voice/LiveVoiceOverlayStateHolderTest.kt index 12fe3898..c98478d9 100644 --- a/agent/app/src/test/java/com/example/appfunctions/agent/ui/voice/LiveVoiceOverlayStateHolderTest.kt +++ b/agent/app/src/test/java/com/example/appfunctions/agent/ui/voice/LiveVoiceOverlayStateHolderTest.kt @@ -17,11 +17,10 @@ package com.example.appfunctions.agent.ui.voice import com.example.appfunctions.agent.data.LlmModel import com.example.appfunctions.agent.data.LlmProviderName -import com.example.appfunctions.agent.data.db.entities.ThreadEntity import com.example.appfunctions.agent.domain.ActiveLiveSession import com.example.appfunctions.agent.domain.LiveAgentOrchestrator import com.example.appfunctions.agent.domain.LiveAgentStatus -import com.example.appfunctions.agent.domain.LlmProvider +import com.example.appfunctions.agent.domain.LiveLlmProvider import com.example.appfunctions.agent.domain.LlmProviderFactory import com.example.appfunctions.agent.domain.appfunction.AppInfo import com.example.appfunctions.agent.domain.appfunction.GetInstalledAppsUseCase @@ -40,7 +39,6 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.test.StandardTestDispatcher @@ -61,12 +59,12 @@ class LiveVoiceOverlayStateHolderTest { private lateinit var manageThreadsUseCase: ManageThreadsUseCase private lateinit var settingsRepository: FakeSettingsRepository private lateinit var llmProviderFactory: LlmProviderFactory - private lateinit var llmProvider: LlmProvider + private lateinit var liveLlmProvider: LiveLlmProvider private lateinit var checkAudioPermissionUseCase: CheckAudioPermissionUseCase private lateinit var getInstalledAppsUseCase: GetInstalledAppsUseCase private val activeSessionFlow = MutableStateFlow(null) - private val testModel = LlmModel(LlmProviderName.GEMINI, "gemini-2.5-flash") + private val testLiveModel = LlmModel(LlmProviderName.GEMINI, "gemini-3.8-live") private val chatAppInfo = AppInfo("com.example.chat", "ChatApp", null) @Before @@ -74,13 +72,14 @@ class LiveVoiceOverlayStateHolderTest { liveAgentOrchestrator = mockk(relaxed = true) manageThreadsUseCase = mockk(relaxed = true) settingsRepository = FakeSettingsRepository() - llmProvider = mockk(relaxed = true) + liveLlmProvider = mockk() llmProviderFactory = mockk(relaxed = true) checkAudioPermissionUseCase = mockk() getInstalledAppsUseCase = mockk() every { liveAgentOrchestrator.activeSession } returns activeSessionFlow - every { llmProviderFactory.getProvider(any()) } returns llmProvider + every { llmProviderFactory.getLiveProvider(any()) } returns liveLlmProvider + every { liveLlmProvider.liveModel } returns testLiveModel every { checkAudioPermissionUseCase() } returns true every { getInstalledAppsUseCase() } returns listOf(chatAppInfo) } @@ -123,12 +122,11 @@ class LiveVoiceOverlayStateHolderTest { } @Test - fun `OnSessionShown without threadId uses existing thread and avoids duplicate restart`() = + fun `OnSessionShown without threadId creates Live-model thread and avoids duplicate restart`() = runTest { - val existingThread = ThreadEntity("thread-existing", 1000L, testModel, null) - every { manageThreadsUseCase.getThreads() } returns flowOf(listOf(existingThread)) + coEvery { manageThreadsUseCase.createThread(testLiveModel) } returns "thread-live" val statusChannel = Channel(Channel.UNLIMITED) - stubRunSession("thread-existing", null, statusChannel.consumeAsFlow()) + stubRunSession("thread-live", null, statusChannel.consumeAsFlow()) val holder = createStateHolder() @@ -136,14 +134,16 @@ class LiveVoiceOverlayStateHolderTest { statusChannel.send(LiveAgentStatus.Listening) advanceUntilIdle() + coVerify(exactly = 1) { manageThreadsUseCase.createThread(testLiveModel) } assertTrue(holder.uiState.value.isVisible) - assertEquals("thread-existing", holder.uiState.value.threadId) + assertEquals("thread-live", holder.uiState.value.threadId) assertEquals(LiveOverlayStatus.Listening, holder.uiState.value.status) // Re-showing without explicit args while active keeps the current session running. holder.onEvent(LiveOverlayUiEvent.OnSessionShown()) advanceUntilIdle() - verify(exactly = 1) { liveAgentOrchestrator.runSession("thread-existing", null) } + coVerify(exactly = 1) { manageThreadsUseCase.createThread(testLiveModel) } + verify(exactly = 1) { liveAgentOrchestrator.runSession("thread-live", null) } holder.onEvent(LiveOverlayUiEvent.OnSessionHidden) advanceUntilIdle() @@ -153,46 +153,47 @@ class LiveVoiceOverlayStateHolderTest { } @Test - fun `OnSessionShown creates default thread from selected provider when no thread exists`() = + fun `OnRetryClicked reuses Live-model thread created for failed session`() = runTest { - settingsRepository.setGeminiApiKey("valid-key") - every { manageThreadsUseCase.getThreads() } returns flowOf(emptyList()) - coEvery { llmProvider.getAvailableModels("valid-key") } returns listOf(testModel) - coEvery { manageThreadsUseCase.createThread(testModel) } returns "thread-created" - val statusChannel = Channel(Channel.UNLIMITED) - stubRunSession("thread-created", null, statusChannel.consumeAsFlow()) - - val holder = createStateHolder() - - holder.onEvent(LiveOverlayUiEvent.OnSessionShown()) - statusChannel.send(LiveAgentStatus.Listening) - advanceUntilIdle() - - coVerify(exactly = 1) { manageThreadsUseCase.createThread(testModel) } - assertEquals("thread-created", holder.uiState.value.threadId) - assertEquals(LiveOverlayStatus.Listening, holder.uiState.value.status) - holder.close() - } - - @Test - fun `OnSessionShown surfaces NoModelAvailable when no thread exists and no model is available`() = - runTest { - every { manageThreadsUseCase.getThreads() } returns flowOf(emptyList()) - coEvery { llmProvider.getAvailableModels(any()) } returns emptyList() + coEvery { manageThreadsUseCase.createThread(testLiveModel) } returns "thread-live" + var calls = 0 + every { liveAgentOrchestrator.runSession("thread-live", null) } answers { + calls++ + if (calls == 1) { + flow { + activeSessionFlow.value = + ActiveLiveSession("thread-live", LiveAgentStatus.Error("Disconnected")) + emit(LiveAgentStatus.Error("Disconnected")) + activeSessionFlow.value = null + awaitCancellation() + } + } else { + flow { + activeSessionFlow.value = + ActiveLiveSession("thread-live", LiveAgentStatus.Listening) + emit(LiveAgentStatus.Listening) + awaitCancellation() + } + } + } val holder = createStateHolder() holder.onEvent(LiveOverlayUiEvent.OnSessionShown()) advanceUntilIdle() - assertTrue(holder.uiState.value.isVisible) + assertEquals("thread-live", holder.uiState.value.threadId) assertEquals( - LiveOverlayStatus.Error.NoModelAvailable(LlmProviderName.GEMINI.displayName), + LiveOverlayStatus.Error.SessionFailed("Disconnected"), holder.uiState.value.status, ) - assertFalse(holder.uiState.value.keepVisibleOnSystemDialogsClose) - coVerify(exactly = 0) { manageThreadsUseCase.createThread(any()) } - verify(exactly = 0) { liveAgentOrchestrator.runSession(any(), any()) } + + holder.onEvent(LiveOverlayUiEvent.OnRetryClicked) + advanceUntilIdle() + + coVerify(exactly = 1) { manageThreadsUseCase.createThread(testLiveModel) } + assertEquals(2, calls) + assertEquals(LiveOverlayStatus.Listening, holder.uiState.value.status) holder.close() }