diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt index 7f0320adb..e6b580bdf 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt @@ -58,10 +58,12 @@ import androidx.compose.material.icons.filled.ArrowDownward import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material.icons.filled.Bolt import androidx.compose.material.icons.filled.CameraAlt +import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Mic import androidx.compose.material.icons.filled.PendingActions @@ -161,9 +163,11 @@ import com.yugahashimoto.andcode.feature.browser.PreviewTarget import com.yugahashimoto.andcode.feature.browser.PreviewUiState import com.yugahashimoto.andcode.feature.workspace.GitHubAutoAttachChips import com.yugahashimoto.andcode.feature.workspace.GitHubReference +import com.yugahashimoto.andcode.feature.workspace.WorkspaceFolders import com.yugahashimoto.andcode.runtime.PermissionResponse import com.yugahashimoto.andcode.runtime.RuntimeTarget import com.yugahashimoto.andcode.runtime.SubscriptionRateLimit +import com.yugahashimoto.andcode.runtime.WorkspaceRef import com.yugahashimoto.andcode.runtime.local.AntigravityPermissionMode import com.yugahashimoto.andcode.runtime.local.ClaudePermissionMode import com.yugahashimoto.andcode.runtime.local.SystemPromptPreset @@ -171,6 +175,7 @@ import com.yugahashimoto.andcode.ui.components.StatusChip import com.yugahashimoto.andcode.ui.components.VolumeMeter import com.yugahashimoto.andcode.ui.components.systemPromptPresetLabel import com.yugahashimoto.andcode.ui.theme.AndCodeTheme +import com.yugahashimoto.andcode.ui.theme.CodeFontFamily import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.serialization.json.JsonPrimitive @@ -313,6 +318,8 @@ fun ChatHomeScreen( canRefreshRateLimits: Boolean = false, rateLimitsRefreshing: Boolean = false, onRefreshRateLimits: () -> Unit = {}, + workspaces: List = emptyList(), + onSelectWorkspace: (String) -> Unit = {}, ) { // Saved state, not plain remember: the Activity is recreated on rotation and other // configuration changes, and a remembered field would come back empty. The TextFieldValue @@ -493,14 +500,20 @@ fun ChatHomeScreen( .fillMaxSize() .background(MaterialTheme.colorScheme.background), ) { + val projectLabel = + remember(state.sessionId, state.sessionDirectory, state.selectedWorkspacePath, workspaces) { + resolveChatProjectLabel(state, workspaces) + } + val canSwitchProject = state.sessionId == null && workspaces.size > 1 CenterAlignedTopAppBar( title = { - Text( - text = state.sessionTitle.ifBlank { stringResource(R.string.chat_home_title) }, - style = MaterialTheme.typography.titleLarge, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, + ChatTopBarTitle( + title = state.sessionTitle.ifBlank { stringResource(R.string.chat_home_title) }, + projectLabel = projectLabel, + workspaces = workspaces, + selectedWorkspacePath = state.selectedWorkspacePath, + canSwitchProject = canSwitchProject, + onSelectWorkspace = onSelectWorkspace, ) }, navigationIcon = { @@ -975,6 +988,153 @@ fun ChatHomeScreen( } } +/** + * Resolves the active project's short display name for the chat header. + * + * An open session is bound to its own [ChatUiState.sessionDirectory], never to whatever workspace + * the composer last happened to select for blank chats. Before the first message creates a + * session, [ChatUiState.selectedWorkspacePath] is the project that will own it. + */ +internal fun resolveChatProjectLabel( + state: ChatUiState, + workspaces: List, +): String? { + val activePath = + if (state.sessionId != null) { + state.sessionDirectory?.takeIf { it.isNotBlank() } + } else { + state.selectedWorkspacePath?.takeIf { it.isNotBlank() } + } ?: return null + val normalized = WorkspaceFolders.normalize(activePath) + val matched = workspaces.firstOrNull { WorkspaceFolders.normalize(it.path) == normalized } + return matched?.name?.takeIf { it.isNotBlank() } ?: WorkspaceFolders.displayName(normalized) +} + +@Composable +private fun ChatTopBarTitle( + title: String, + projectLabel: String?, + workspaces: List, + selectedWorkspacePath: String?, + canSwitchProject: Boolean, + onSelectWorkspace: (String) -> Unit, +) { + var projectMenuExpanded by remember { mutableStateOf(false) } + LaunchedEffect(canSwitchProject) { + if (!canSwitchProject) projectMenuExpanded = false + } + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = title, + style = + if (projectLabel != null) { + MaterialTheme.typography.titleMedium + } else { + MaterialTheme.typography.titleLarge + }, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (projectLabel != null) { + Box { + Row( + modifier = + Modifier + .clip(RoundedCornerShape(100.dp)) + .then( + if (canSwitchProject) { + Modifier.clickable { projectMenuExpanded = true } + } else { + Modifier + }, + ) + .padding(horizontal = 6.dp, vertical = 1.dp) + .testTag("chat-project-label"), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + Icon( + imageVector = Icons.Default.Folder, + contentDescription = stringResource(R.string.cd_folder), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(12.dp), + ) + Text( + text = projectLabel, + modifier = Modifier.weight(1f, fill = false), + style = MaterialTheme.typography.labelSmall, + fontFamily = CodeFontFamily, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (canSwitchProject) { + Icon( + imageVector = Icons.Default.ArrowDropDown, + contentDescription = stringResource(R.string.cd_expand_dropdown), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(14.dp), + ) + } + } + if (canSwitchProject) { + DropdownMenu( + expanded = projectMenuExpanded, + onDismissRequest = { projectMenuExpanded = false }, + ) { + val normalizedSelected = selectedWorkspacePath?.let(WorkspaceFolders::normalize) + workspaces.forEach { workspace -> + val selected = + normalizedSelected != null && + WorkspaceFolders.normalize(workspace.path) == normalizedSelected + DropdownMenuItem( + text = { + Text( + text = workspace.name, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + leadingIcon = { + Icon( + imageVector = Icons.Default.Folder, + contentDescription = null, + tint = + if (selected) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + modifier = Modifier.size(18.dp), + ) + }, + trailingIcon = + if (selected) { + { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(16.dp), + ) + } + } else { + null + }, + onClick = { + projectMenuExpanded = false + onSelectWorkspace(workspace.path) + }, + ) + } + } + } + } + } + } +} + /** * Shown while a subagent session is open. Subagent chats are opened from the parent conversation, * so they need an explicit way back to the main agent. diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt index a42889ecc..40681196e 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt @@ -491,6 +491,7 @@ private fun extractPatchFiles(state: Map): List { data class ParentSessionRef( val id: String, val title: String = "", + val directory: String? = null, ) data class ChatUiState( @@ -1116,6 +1117,7 @@ class ChatViewModel( sessionId: String, title: String = "", parent: ParentSessionRef? = null, + directory: String? = null, ) { val currentBackend = backend ?: return // A blank id is not a session: loading it would ask the runtime for `session//message` and @@ -1151,7 +1153,7 @@ class ChatViewModel( messages = emptyList(), permissions = emptyList(), pendingQuestions = emptyList(), - sessionDirectory = null, + sessionDirectory = directory?.takeIf { dir -> dir.isNotBlank() }, isRunning = if (switchingSession) alreadyRunning else it.isRunning, isThinking = if (switchingSession) alreadyRunning else it.isThinking, dismissedTodoBarId = null, @@ -1194,16 +1196,17 @@ class ChatViewModel( fun openSubagentSession( sessionId: String, title: String = "", + directory: String? = null, ) { val current = _uiState.value - val parent = current.sessionId?.let { ParentSessionRef(it, current.sessionTitle) } - openSession(sessionId, title, parent) + val parent = current.sessionId?.let { ParentSessionRef(it, current.sessionTitle, current.sessionDirectory) } + openSession(sessionId, title, parent, directory) } /** Returns from a subagent session to the session that spawned it. */ fun openParentSession() { val parent = _uiState.value.parentSession ?: return - openSession(parent.id, parent.title) + openSession(parent.id, parent.title, directory = parent.directory) } /** @@ -1216,13 +1219,15 @@ class ChatViewModel( val parentId = runCatching { currentBackend.session(sessionId) }.getOrNull()?.parentId ?: return@launch - val parentTitle = - runCatching { currentBackend.session(parentId) }.getOrNull()?.title.orEmpty() + val parentSession = runCatching { currentBackend.session(parentId) }.getOrNull() + val parentTitle = parentSession?.title.orEmpty() _uiState.update { state -> if (state.sessionId != sessionId) { state } else { - state.copy(parentSession = ParentSessionRef(parentId, parentTitle)) + state.copy( + parentSession = ParentSessionRef(parentId, parentTitle, parentSession?.directory), + ) } } } @@ -1614,7 +1619,11 @@ class ChatViewModel( if (session != null) { applyDraftSystemPrompt(session.id, draftGeneration) _uiState.update { - it.copy(sessionId = session.id, sessionTitle = session.title) + it.copy( + sessionId = session.id, + sessionTitle = session.title, + sessionDirectory = session.directory?.takeIf { dir -> dir.isNotBlank() } ?: it.selectedWorkspacePath, + ) } onSessionCreated() } @@ -1844,7 +1853,11 @@ class ChatViewModel( if (session != null) { applyDraftSystemPrompt(session.id, draftGeneration) _uiState.update { - it.copy(sessionId = session.id, sessionTitle = session.title) + it.copy( + sessionId = session.id, + sessionTitle = session.title, + sessionDirectory = session.directory?.takeIf { dir -> dir.isNotBlank() } ?: it.selectedWorkspacePath, + ) } onSessionCreated() } @@ -2162,13 +2175,14 @@ class ChatViewModel( private fun refreshPendingQuestions(sessionId: String) { val currentBackend = backend ?: return viewModelScope.launch { - val directory = + val sessionDirectory = runCatching { currentBackend.session(sessionId).directory } .getOrNull() - ?: _uiState.value.selectedWorkspacePath - if (directory != null && _uiState.value.sessionId == sessionId) { - _uiState.update { it.copy(sessionDirectory = directory) } + ?.takeIf { it.isNotBlank() } + if (sessionDirectory != null && _uiState.value.sessionId == sessionId) { + _uiState.update { it.copy(sessionDirectory = sessionDirectory) } } + val directory = sessionDirectory ?: _uiState.value.sessionDirectory ?: _uiState.value.selectedWorkspacePath var fetched: List? = null for (attempt in 0 until PENDING_QUESTION_REFRESH_ATTEMPTS) { if (_uiState.value.sessionId != sessionId) return@launch diff --git a/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt b/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt index 76baa5454..6251219b6 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt @@ -792,7 +792,12 @@ fun AndCodeApp( chatViewModel.setAutoAcceptPermissions(preferences.autoAcceptPermissions) } - LaunchedEffect(selectedRuntime?.id, workspaceState.workspaces, chatState.sessionId) { + LaunchedEffect( + selectedRuntime?.id, + workspaceState.workspaces, + chatState.sessionId, + chatState.selectedWorkspacePath, + ) { if (chatState.sessionId != null) return@LaunchedEffect val currentPath = chatState.selectedWorkspacePath val available = workspaceState.workspaces @@ -1287,7 +1292,12 @@ fun AndCodeApp( LaunchedEffect(pendingSession, selectedRuntime?.id) { val pending = pendingSession ?: return@LaunchedEffect if (selectedRuntime == null) return@LaunchedEffect - chatViewModel.openSession(pending.first, pending.second) + val knownDirectory = + app.catalogRepository.allSessions.value + .firstOrNull { it.session.id == pending.first } + ?.session + ?.directory + chatViewModel.openSession(pending.first, pending.second, directory = knownDirectory) pendingSession = null } LaunchedEffect(pendingHandoffPrompt, selectedRuntime?.id, handoffReady) { @@ -1464,6 +1474,8 @@ fun AndCodeApp( } } }, + workspaces = workspaceState.workspaces, + onSelectWorkspace = chatViewModel::selectWorkspace, onMic = requestVoiceInput, onNewChat = { pendingSession = null @@ -1491,6 +1503,7 @@ fun AndCodeApp( chatViewModel.openSubagentSession( childSessionId, childSession?.title ?: childSessionId, + directory = childSession?.directory, ) }, onReturnToParentSession = { diff --git a/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatProjectLabelTest.kt b/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatProjectLabelTest.kt new file mode 100644 index 000000000..1754bb46b --- /dev/null +++ b/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatProjectLabelTest.kt @@ -0,0 +1,71 @@ +package com.yugahashimoto.andcode.feature.chat + +import com.yugahashimoto.andcode.runtime.WorkspaceRef +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ChatProjectLabelTest { + @Test + fun `blank chat uses selected workspace name when it matches a known workspace`() { + val label = + resolveChatProjectLabel( + state = ChatUiState(selectedWorkspacePath = "/workspace/and-code"), + workspaces = listOf(WorkspaceRef("/workspace/and-code", "AndCode", "/workspace/and-code")), + ) + + assertEquals("AndCode", label) + } + + @Test + fun `blank chat falls back to folder display name when workspace is not in the list`() { + val label = + resolveChatProjectLabel( + state = ChatUiState(selectedWorkspacePath = "/workspace/opendots-android/"), + workspaces = emptyList(), + ) + + assertEquals("opendots-android", label) + } + + @Test + fun `open session uses sessionDirectory and ignores selectedWorkspacePath`() { + val label = + resolveChatProjectLabel( + state = + ChatUiState( + sessionId = "s1", + sessionDirectory = "/workspace/alpha", + selectedWorkspacePath = "/workspace/beta", + ), + workspaces = + listOf( + WorkspaceRef("/workspace/alpha", "alpha", "/workspace/alpha"), + WorkspaceRef("/workspace/beta", "beta", "/workspace/beta"), + ), + ) + + assertEquals("alpha", label) + } + + @Test + fun `open session with no sessionDirectory returns null instead of leaking selectedWorkspacePath`() { + val label = + resolveChatProjectLabel( + state = + ChatUiState( + sessionId = "s1", + sessionDirectory = null, + selectedWorkspacePath = "/workspace/beta", + ), + workspaces = listOf(WorkspaceRef("/workspace/beta", "beta", "/workspace/beta")), + ) + + assertNull(label) + } + + @Test + fun `blank chat with no selected workspace returns null`() { + assertNull(resolveChatProjectLabel(ChatUiState(), workspaces = emptyList())) + } +} diff --git a/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatViewModelTest.kt b/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatViewModelTest.kt index 18a511f9b..77bb0c031 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatViewModelTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatViewModelTest.kt @@ -2133,6 +2133,46 @@ class ChatViewModelTest { assertEquals("look", request.text) } + @Test + fun `creating a session records its directory on uiState`() = + runTest(dispatcher) { + val backend = FakeBackend() + val viewModel = ChatViewModel(backend) + advanceUntilIdle() + + viewModel.selectWorkspace("/workspace/and-code") + viewModel.sendMessage("hello") + advanceUntilIdle() + + assertEquals("/workspace/and-code", viewModel.uiState.value.sessionDirectory) + } + + @Test + fun `opening a session preserves caller directory until backend confirms it`() = + runTest(dispatcher) { + val backend = + FakeBackend().apply { + sessionsById = + mapOf( + "s-parent" to + OpenCodeSession( + id = "s-parent", + title = "Parent", + directory = "/workspace/alpha", + ), + ) + } + val viewModel = ChatViewModel(backend) + advanceUntilIdle() + viewModel.selectWorkspace("/workspace/beta") + + viewModel.openSession("s-parent", "Parent", directory = "/workspace/alpha") + assertEquals("/workspace/alpha", viewModel.uiState.value.sessionDirectory) + + advanceUntilIdle() + assertEquals("/workspace/alpha", viewModel.uiState.value.sessionDirectory) + } + private class InMemoryDraftStore : DraftStore { private val drafts = mutableMapOf()