From 2aee16b2ebbf4d9c607840e29f83755fd444fd9f Mon Sep 17 00:00:00 2001 From: kirillk Date: Wed, 19 Aug 2026 13:18:49 -0400 Subject: [PATCH 01/30] fix(jetbrains): show tool window content as tabs --- .changeset/jetbrains-tool-window-tabs.md | 5 +++++ .../kilocode/client/KiloToolWindowFactory.kt | 16 ++-------------- .../resources/messages/KiloBundle.properties | 5 ++--- .../client/KiloToolWindowFactoryTest.kt | 19 +++++-------------- 4 files changed, 14 insertions(+), 31 deletions(-) create mode 100644 .changeset/jetbrains-tool-window-tabs.md diff --git a/.changeset/jetbrains-tool-window-tabs.md b/.changeset/jetbrains-tool-window-tabs.md new file mode 100644 index 000000000000..6f64493e90d7 --- /dev/null +++ b/.changeset/jetbrains-tool-window-tabs.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Show the JetBrains tool window Chat and Agents views as tabs with shorter labels. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt index 9897495b1b8d..bbf25fd8c03e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt @@ -14,7 +14,6 @@ import ai.kilocode.client.agentManager.worktree.WorktreeController import ai.kilocode.client.agentManager.AgentManagerPanel import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.log.KiloLog -import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DataProvider @@ -24,10 +23,10 @@ import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow +import com.intellij.openapi.wm.ToolWindowContentUiType import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.platform.project.projectIdOrNull import com.intellij.openapi.wm.impl.content.ToolWindowContentUi -import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManagerEvent import com.intellij.ui.content.ContentManagerListener import com.intellij.ui.content.ContentFactory @@ -36,7 +35,6 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.awt.BorderLayout -import java.awt.ComponentOrientation import javax.swing.JPanel /** @@ -122,6 +120,7 @@ internal class KiloToolWindowSetupService( } agent.add(agentManagerPanel.component, BorderLayout.CENTER) + toolWindow.setContentUiType(ToolWindowContentUiType.TABBED, null) // Hide the "Kilo Code" id label in the header so only the content tabs remain. toolWindow.component.putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true") @@ -132,7 +131,6 @@ internal class KiloToolWindowSetupService( chatContent.setPreferredFocusedComponent { manager.defaultFocusedComponent } val agentContent = factory.createContent(agent, KiloBundle.message("sidePanel.mode.agentManager"), false) agentContent.applySidePanelMode(SidePanelMode.AGENT_MANAGER) - agentContent.applyAgentManagerBetaBadge() agentContent.setPreferredFocusedComponent { agentManagerPanel.component } toolWindow.contentManager.addContent(chatContent) toolWindow.contentManager.addContent(agentContent) @@ -165,13 +163,3 @@ internal class KiloToolWindowSetupService( } } } - -internal fun Content.applyAgentManagerBetaBadge() { - icon = AllIcons.General.Beta - description = KiloBundle.message("sidePanel.mode.agentManager.beta.description") - putUserData(ToolWindow.SHOW_CONTENT_ICON, true) - // TAB_LABEL_ORIENTATION_KEY is @ApiStatus.Experimental and may change or disappear between IDE - // releases; we declare no untilBuild cap. Failure is benign: putUserData no-ops and the Beta - // icon falls back to the left of the tab label. - putUserData(Content.TAB_LABEL_ORIENTATION_KEY, ComponentOrientation.RIGHT_TO_LEFT) -} diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties index 7af9b0b901cb..428a66bd5dce 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties @@ -341,9 +341,8 @@ history.error.local.delete=Failed to delete session history.error.local.rename=Failed to rename session history.error.cloud.delete=Cloud sessions cannot be deleted yet -sidePanel.mode.branch=AI Chat -sidePanel.mode.agentManager=Agent Manager -sidePanel.mode.agentManager.beta.description=Agent Manager (Beta) +sidePanel.mode.branch=Chat +sidePanel.mode.agentManager=Agents worktree.empty=No worktrees worktree.delete.action=Delete worktree worktree.delete.confirm.message=Delete worktree "{0}"? diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/KiloToolWindowFactoryTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/KiloToolWindowFactoryTest.kt index d507a7727055..618eac992d8d 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/KiloToolWindowFactoryTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/KiloToolWindowFactoryTest.kt @@ -3,29 +3,20 @@ package ai.kilocode.client import ai.kilocode.client.agentManager.SidePanelKeys import ai.kilocode.client.agentManager.SidePanelMode import ai.kilocode.client.agentManager.applySidePanelMode +import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.util.edtWait -import com.intellij.icons.AllIcons -import com.intellij.openapi.wm.ToolWindow import com.intellij.testFramework.fixtures.BasePlatformTestCase -import com.intellij.ui.content.Content import com.intellij.ui.content.ContentFactory -import java.awt.ComponentOrientation import javax.swing.JPanel class KiloToolWindowFactoryTest : BasePlatformTestCase() { - fun `test agent manager content uses beta badge metadata`() = edtWait { - val content = ContentFactory.getInstance().createContent(JPanel(), "Agent Manager", false) - - content.applyAgentManagerBetaBadge() - - assertSame(AllIcons.General.Beta, content.icon) - assertEquals("Agent Manager (Beta)", content.description) - assertEquals(true, content.getUserData(ToolWindow.SHOW_CONTENT_ICON)) - assertEquals(ComponentOrientation.RIGHT_TO_LEFT, content.getUserData(Content.TAB_LABEL_ORIENTATION_KEY)) + fun `test content labels are short`() { + assertEquals("Chat", KiloBundle.message("sidePanel.mode.branch")) + assertEquals("Agents", KiloBundle.message("sidePanel.mode.agentManager")) } fun `test content records side panel mode`() = edtWait { - val content = ContentFactory.getInstance().createContent(JPanel(), "Branch", false) + val content = ContentFactory.getInstance().createContent(JPanel(), "Chat", false) content.applySidePanelMode(SidePanelMode.CHAT) From f73f9474ec9ee893ac58fca0b65d55009d451daf Mon Sep 17 00:00:00 2001 From: kirillk Date: Wed, 19 Aug 2026 15:53:29 -0400 Subject: [PATCH 02/30] fix(jetbrains): pad empty session recents --- .changeset/jetbrains-empty-recents-padding.md | 5 +++++ .../ai/kilocode/client/session/ui/empty/RecentsList.kt | 1 + 2 files changed, 6 insertions(+) create mode 100644 .changeset/jetbrains-empty-recents-padding.md diff --git a/.changeset/jetbrains-empty-recents-padding.md b/.changeset/jetbrains-empty-recents-padding.md new file mode 100644 index 000000000000..5fb8497d88a5 --- /dev/null +++ b/.changeset/jetbrains-empty-recents-padding.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Add standard horizontal padding to the empty chat recent sessions list. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/empty/RecentsList.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/empty/RecentsList.kt index 039fe94158a2..587152ae98e8 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/empty/RecentsList.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/empty/RecentsList.kt @@ -74,6 +74,7 @@ internal class RecentsList( init { isOpaque = false + border = JBUI.Borders.empty(0, UiStyle.Gap.pad(), 0, UiStyle.Gap.pad()) add(title, BorderLayout.NORTH) add(list, BorderLayout.CENTER) setSessions(sessions) From 3e152b75fd98ac2cf5f56ddbfa0b94b017b12e45 Mon Sep 17 00:00:00 2001 From: kirillk Date: Wed, 19 Aug 2026 16:47:20 -0400 Subject: [PATCH 03/30] feat(jetbrains): update agent manager worktree list --- .changeset/wet-lemons-walk.md | 5 ++ .../client/agentManager/AgentManagerPanel.kt | 40 +++++++++++----- .../worktree/WorktreeController.kt | 6 +++ .../agentManager/worktree/WorktreeIcons.kt | 11 ++++- .../main/resources/icons/worktreeRunning.svg | 6 +++ .../resources/icons/worktreeRunning_dark.svg | 6 +++ .../resources/messages/KiloBundle.properties | 1 + .../agentManager/AgentManagerPanelTest.kt | 48 +++++++++++++++++-- .../agentManager/WorktreeControllerTest.kt | 32 +++++++++++-- 9 files changed, 136 insertions(+), 19 deletions(-) create mode 100644 .changeset/wet-lemons-walk.md create mode 100644 packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning.svg create mode 100644 packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning_dark.svg diff --git a/.changeset/wet-lemons-walk.md b/.changeset/wet-lemons-walk.md new file mode 100644 index 000000000000..c26343304b89 --- /dev/null +++ b/.changeset/wet-lemons-walk.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Show the current branch first in Agent Manager and replace worktree activity tags with status icons. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 7bada546ebf9..9b16a8fcf961 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -17,7 +17,6 @@ import ai.kilocode.client.agentManager.worktree.ensureWorktreeSessionEditorKind import ai.kilocode.client.agentManager.worktree.prTooltip import ai.kilocode.client.agentManager.worktree.normalizeWorktreePath import ai.kilocode.client.agentManager.worktree.style -import ai.kilocode.client.agentManager.worktree.worktreeActivityBadge import ai.kilocode.client.agentManager.worktree.worktreeSessionParams import ai.kilocode.client.diff.KiloDiffEditorKind import ai.kilocode.client.diff.diffParams @@ -202,7 +201,7 @@ class AgentManagerPanel( private fun open(item: WorktreeDto, focus: Boolean) { val target = project ?: return - if (item.main || controller.isPending(item.id)) return + if (controller.isPending(item.id)) return ensureWorktreeSessionEditorKind() target.service().open(WorktreeSessionEditorKind.ID, worktreeSessionParams(item), focus) } @@ -350,13 +349,31 @@ class AgentManagerPanel( private fun sync() { val key = selected + val current = controller.current?.let { item -> + WorktreeRow( + item, + pending = false, + deleting = false, + kind = controller.kind(item.path), + stats = null, + pr = null, + current = true, + ) + } list.update( - (0 until controller.model.size).map { + listOfNotNull(current) + (0 until controller.model.size).map { val item = controller.model.getElementAt(it) val key = normalizeWorktreePath(item.path) val pull = prs[key] service().putPr(item.path, pull) - WorktreeRow(item, controller.isPending(item.id), controller.isDeleting(item.id), controller.kind(item.path), stats[key], pull) + WorktreeRow( + item, + controller.isPending(item.id), + controller.isDeleting(item.id), + controller.kind(item.path), + stats[key], + pull, + ) }, ActiveListSelection.PreserveNoScroll, ) @@ -465,19 +482,16 @@ class AgentManagerPanel( val kind: SessionActivityKind?, val stats: WorktreeStatsDto?, val pr: WorktreePrDto?, + val current: Boolean = false, ) : ActiveListItem { override val key: String get() = dto.id - override val title: String get() = WorktreeTitle.text(dto.name, dto.path, pr) + override val title: String get() = if (current) dto.branch else WorktreeTitle.text(dto.name, dto.path, pr) override val description: String get() = WorktreeTitle.fallback(dto.path) override val tooltip: String? get() = null - override val icon = WorktreeIcons.forRow(dto.locked, pending) + override val icon = WorktreeIcons.forRow(dto.locked, pending, kind) + override val section: String? get() = if (current) null else KiloBundle.message("worktree.section.local") override val search: String get() = listOfNotNull(dto.name, dto.branch, dto.path, dto.lockReason).joinToString(" ") private val customName: String? get() = WorktreeTitle.custom(dto.name, dto.path) - override val badges: List - get() { - if (pending || deleting) return emptyList() - return listOfNotNull(kind?.let(::worktreeActivityBadge)) - } override val metrics: ActiveListMetrics? get() { if (pending || deleting) return null @@ -503,7 +517,8 @@ class AgentManagerPanel( deleting == row.deleting && kind == row.kind && stats == row.stats && - pr == row.pr + pr == row.pr && + current == row.current } override fun hashCode(): Int { @@ -513,6 +528,7 @@ class AgentManagerPanel( result = 31 * result + (kind?.hashCode() ?: 0) result = 31 * result + (stats?.hashCode() ?: 0) result = 31 * result + (pr?.hashCode() ?: 0) + result = 31 * result + current.hashCode() return result } } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt index f50e94d08c68..a3d58205b466 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt @@ -62,6 +62,11 @@ class WorktreeController( var branches: List = emptyList() private set + /** Primary worktree for the current branch, shown above local worktrees in Agent Manager. */ + @Volatile + var current: WorktreeDto? = null + private set + /** Every known branch name, used to keep generated worktree names collision-free. */ @Volatile private var known: Set = emptySet() @@ -81,6 +86,7 @@ class WorktreeController( val main = result.worktrees.firstOrNull { it.main } val extra = result.worktrees.filter { !it.main } val rows = extra + pending.values + current = main model.replaceAll(rows) cache().putAll(rows) defaultBranch = main?.branch?.takeIf { it.isNotBlank() && it != "(detached)" } ?: "main" diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt index 586097001fbb..af1b3ca7dbaf 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt @@ -1,16 +1,25 @@ package ai.kilocode.client.agentManager.worktree +import ai.kilocode.client.session.SessionActivityKind import com.intellij.openapi.util.IconLoader import com.intellij.ui.AnimatedIcon +import com.intellij.util.IconUtil import javax.swing.Icon internal object WorktreeIcons { val branch: Icon = IconLoader.getIcon("/icons/worktreeBranch.svg", WorktreeIcons::class.java) val locked: Icon = IconLoader.getIcon("/icons/worktreeLock.svg", WorktreeIcons::class.java) + val running: Icon = IconLoader.getIcon("/icons/worktreeRunning.svg", WorktreeIcons::class.java) + private val prompt: Icon = IconLoader.getIcon("/icons/scroll-question.svg", WorktreeIcons::class.java) + val question: Icon = IconUtil.scale(prompt, null, branch.iconWidth.toFloat() / prompt.iconWidth.toFloat()) val spinner: Icon = AnimatedIcon.Default.INSTANCE - fun forRow(locked: Boolean, pending: Boolean): Icon = when { + fun forRow(locked: Boolean, pending: Boolean, kind: SessionActivityKind? = null): Icon = when { pending -> spinner + kind == SessionActivityKind.RUNNING -> running + kind == SessionActivityKind.QUESTION || + kind == SessionActivityKind.PLAN || + kind == SessionActivityKind.PERMISSION -> question locked -> this.locked else -> branch } diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning.svg new file mode 100644 index 000000000000..cba67f6b29a3 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning_dark.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning_dark.svg new file mode 100644 index 000000000000..600330d6e209 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning_dark.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties index 428a66bd5dce..46c9a429c6cc 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties @@ -344,6 +344,7 @@ history.error.cloud.delete=Cloud sessions cannot be deleted yet sidePanel.mode.branch=Chat sidePanel.mode.agentManager=Agents worktree.empty=No worktrees +worktree.section.local=Local worktrees worktree.delete.action=Delete worktree worktree.delete.confirm.message=Delete worktree "{0}"? worktree.delete.confirm.detail=This removes the working tree and its branch. diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index 27ab26a287d1..3a5c21ef1d4e 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -6,6 +6,7 @@ import ai.kilocode.client.agentManager.worktree.GhStatusCoordinator import ai.kilocode.client.agentManager.worktree.WorktreeController import ai.kilocode.client.agentManager.worktree.WorktreeEditorMatcher import ai.kilocode.client.agentManager.worktree.WorktreeEditorMatchers +import ai.kilocode.client.agentManager.worktree.WorktreeIcons import ai.kilocode.client.agentManager.worktree.WorktreeNameCache import ai.kilocode.client.agentManager.worktree.WorktreeSessionEditorKind import ai.kilocode.client.agentManager.worktree.WorktreeStatusService @@ -17,7 +18,6 @@ import ai.kilocode.client.testing.TestCoroutines import ai.kilocode.client.testing.pumpEdt import ai.kilocode.client.testing.TestUiTimers import ai.kilocode.client.testing.fire -import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.client.ui.list.ActiveListBadge import ai.kilocode.client.ui.list.ActiveListItem import ai.kilocode.client.ui.list.ActiveListMetrics @@ -174,6 +174,46 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(false, file.getUserData(KiloVfsManager.FOCUS)) } + fun `test current branch row appears first and opens session editor`() { + val main = WorktreeDto("/repo", "repo", "main", "/repo", main = true) + val item = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") + rpc.listed += main + rpc.listed += item + val controller = WorktreeController(service, "/repo", coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + + val current = row(panel, 0) + assertEquals("main", current.title) + assertEquals("repo", current.description) + assertNull(current.section) + assertNull(current.metrics) + assertEquals("Local worktrees", row(panel, 1).section) + + val list = edt { UIUtil.findComponentOfType(panel, JBList::class.java)!! } + edt { + list.setSize(400, 120) + list.doLayout() + val bounds = list.getCellBounds(0, 0) + fire(list, MouseEvent( + list, + MouseEvent.MOUSE_CLICKED, + System.currentTimeMillis(), + 0, + bounds.x + 8, + bounds.y + bounds.height / 2, + 1, + false, + MouseEvent.BUTTON1, + )) + } + + val file = edt { FileEditorManager.getInstance(project).openFiles.single() as KiloVirtualFile } + assertEquals(WorktreeSessionEditorKind.ID, file.path.kind) + assertEquals(main.path, file.path.params["path"]) + } + fun `test refresh preserves selected worktree across model replace`() { val first = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") val second = WorktreeDto("/repo/.kilo/worktrees/feature-y", "feature-y", "feature/y", "/repo/.kilo/worktrees/feature-y") @@ -396,7 +436,7 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(a.path, file.path.params["path"]) } - fun `test worktree row shows activity badge for matching directory`() { + fun `test worktree row shows activity icon for matching directory`() { val item = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") val activity = MutableStateFlow(mapOf( "ses_1" to SessionActivityDto(item.path, SessionActivityKindDto.QUESTION), @@ -408,7 +448,8 @@ class AgentManagerPanelTest : BasePlatformTestCase() { flush() val row = row(panel, 0) - assertEquals(listOf(ActiveListBadge(SessionActivityKind.QUESTION.label(), SessionActivityKind.QUESTION.style())), row.badges) + assertSame(WorktreeIcons.question, row.icon) + assertEquals(emptyList(), row.badges) } fun `test worktree row shows metrics from status service`() { @@ -528,6 +569,7 @@ class AgentManagerPanelTest : BasePlatformTestCase() { flush() val pending = row(panel, 0) + assertSame(WorktreeIcons.spinner, pending.icon) assertEquals(emptyList(), pending.badges) gate.complete(Unit) flush() diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt index 3695c5dfb29c..138fd8418d8a 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt @@ -56,6 +56,7 @@ class WorktreeControllerTest : BasePlatformTestCase() { assertEquals(1, controller.model.size) assertEquals("feature/x", controller.model.getElementAt(0).branch) + assertEquals("/repo", controller.current?.path) } fun `test service open routes the directory to the backend rpc`() { @@ -348,17 +349,42 @@ class WorktreeControllerTest : BasePlatformTestCase() { } } - fun `test worktree icons prefer pending then locked then branch`() { - assertSame(WorktreeIcons.spinner, WorktreeIcons.forRow(locked = false, pending = true)) + fun `test worktree icons prefer pending then activity then locked then branch`() { + assertSame( + WorktreeIcons.spinner, + WorktreeIcons.forRow(locked = false, pending = true, kind = SessionActivityKind.RUNNING), + ) + assertSame( + WorktreeIcons.running, + WorktreeIcons.forRow(locked = true, pending = false, kind = SessionActivityKind.RUNNING), + ) + assertSame( + WorktreeIcons.question, + WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.QUESTION), + ) + assertSame( + WorktreeIcons.question, + WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.PLAN), + ) + assertSame( + WorktreeIcons.question, + WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.PERMISSION), + ) assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(locked = true, pending = false)) assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(locked = false, pending = false)) } - fun `test branch and lock icons load at the same size`() { + fun `test worktree icons load at the same size`() { assertTrue("branch icon should load", WorktreeIcons.branch.iconWidth > 0) assertTrue("lock icon should load", WorktreeIcons.locked.iconWidth > 0) + assertTrue("running icon should load", WorktreeIcons.running.iconWidth > 0) + assertTrue("question icon should load", WorktreeIcons.question.iconWidth > 0) assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.locked.iconWidth) assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.locked.iconHeight) + assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.running.iconWidth) + assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.running.iconHeight) + assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.question.iconWidth) + assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.question.iconHeight) } fun `test worktree delete eligibility excludes missing main and pending rows`() { From 89b20c694bab9aeb5b49317607845e49acfc4543 Mon Sep 17 00:00:00 2001 From: kirillk Date: Wed, 19 Aug 2026 19:55:39 -0400 Subject: [PATCH 04/30] feat(jetbrains): unify activity status colors and add error state Drive the worktree row icon and text badge from one color token per activity state, add an error state end-to-end (shared DTO, backend activity tracking, frontend aggregate), and show a notification dot on the Agents tab when a session needs attention. --- .changeset/wet-lemons-walk.md | 2 +- .../backend/app/KiloBackendActivityManager.kt | 6 ++ .../app/KiloBackendActivityManagerTest.kt | 32 ++++++++++ .../kilocode/client/KiloToolWindowFactory.kt | 14 ++++ .../client/agentManager/AgentAttention.kt | 16 +++++ .../agentManager/worktree/WorktreeActivity.kt | 6 +- .../agentManager/worktree/WorktreeIcons.kt | 9 +-- .../kilocode/client/session/ActivityIcon.kt | 64 +++++++++++++++++++ .../client/session/SessionActivityKind.kt | 10 ++- .../ai/kilocode/client/ui/AttentionDotIcon.kt | 27 ++++++++ .../kotlin/ai/kilocode/client/ui/UiStyle.kt | 32 ++++++++-- .../main/resources/icons/worktreeRunning.svg | 6 -- .../resources/icons/worktreeRunning_dark.svg | 6 -- .../resources/messages/KiloBundle.properties | 1 + .../client/agentManager/AgentAttentionTest.kt | 27 ++++++++ .../agentManager/AgentManagerPanelTest.kt | 17 ++++- .../agentManager/WorktreeControllerTest.kt | 25 ++++---- .../worktree/WorktreeActivityTest.kt | 15 +++++ .../ai/kilocode/client/ui/UiStyleTest.kt | 11 ++-- .../kotlin/ai/kilocode/rpc/dto/SessionDto.kt | 1 + 20 files changed, 281 insertions(+), 46 deletions(-) create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentAttention.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ActivityIcon.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/AttentionDotIcon.kt delete mode 100644 packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning.svg delete mode 100644 packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning_dark.svg create mode 100644 packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentAttentionTest.kt diff --git a/.changeset/wet-lemons-walk.md b/.changeset/wet-lemons-walk.md index c26343304b89..7ca02de73577 100644 --- a/.changeset/wet-lemons-walk.md +++ b/.changeset/wet-lemons-walk.md @@ -2,4 +2,4 @@ "@kilocode/kilo-jetbrains": patch --- -Show the current branch first in Agent Manager and replace worktree activity tags with status icons. +Show the current branch first in Agent Manager and replace worktree activity tags with status icons. Running, question, and error activity now share one color between the row icon and the text badge, add an error state, and surface a notification dot on the Agents tab when a session needs attention. diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendActivityManager.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendActivityManager.kt index c49cc73e3c9f..d8bfd6d1d11c 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendActivityManager.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendActivityManager.kt @@ -31,6 +31,7 @@ class KiloBackendActivityManager( ) { private val permissions = mutableMapOf>() private val questions = mutableMapOf>() + private val errors = mutableSetOf() private val lock = Any() private val _activity = MutableStateFlow>(emptyMap()) val activity: StateFlow> = _activity.asStateFlow() @@ -72,6 +73,7 @@ class KiloBackendActivityManager( synchronized(lock) { permissions.clear() questions.clear() + errors.clear() } _activity.value = emptyMap() log.info("Activity manager stopped") @@ -84,6 +86,8 @@ class KiloBackendActivityManager( is ChatEventDto.QuestionAsked -> questions.getOrPut(event.sessionID) { mutableMapOf() }[event.request.id] = plan(event) is ChatEventDto.QuestionReplied -> removeMap(questions, event.sessionID, event.requestID) is ChatEventDto.QuestionRejected -> removeMap(questions, event.sessionID, event.requestID) + is ChatEventDto.Error -> event.sessionID?.let { errors.add(it) } + is ChatEventDto.TurnOpen -> errors.remove(event.sessionID) is ChatEventDto.SessionIdle -> clear(event.sessionID) is ChatEventDto.SessionStatusChanged -> if (event.status.type == "idle") clear(event.sessionID) else -> Unit @@ -96,6 +100,7 @@ class KiloBackendActivityManager( ids.addAll(current.filterValues { it.type == "busy" }.keys) ids.addAll(permissions.keys) ids.addAll(questions.keys) + ids.addAll(errors) _activity.value = ids.mapNotNull { id -> val dir = directory(id) ?: return@mapNotNull null val kind = kind(id, current[id]?.type == "busy") ?: return@mapNotNull null @@ -110,6 +115,7 @@ class KiloBackendActivityManager( if (pending.values.any { it }) return SessionActivityKindDto.PLAN return SessionActivityKindDto.QUESTION } + if (id in errors) return SessionActivityKindDto.ERROR if (busy) return SessionActivityKindDto.RUNNING return null } diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt index 32616590907a..ba13390a1cda 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt @@ -89,6 +89,38 @@ class KiloBackendActivityManagerTest { assertFalse("ses_1" in manager.activity.value) } + @Test + fun `error persists through idle and clears on next turn`() = runBlocking { + directories["ses_1"] = "/repo/wt" + statuses.value = mapOf("ses_1" to SessionStatusDto("busy")) + start() + + events.emit(ChatEventDto.Error("ses_1")) + await("ses_1", SessionActivityKindDto.ERROR) + + // Turn ends: session goes idle but the error must stay visible. + statuses.value = mapOf("ses_1" to SessionStatusDto("idle")) + events.emit(ChatEventDto.SessionIdle("ses_1")) + await("ses_1", SessionActivityKindDto.ERROR) + + // A new turn clears the error. + events.emit(ChatEventDto.TurnOpen("ses_1")) + withTimeout(5_000) { manager.activity.first { "ses_1" !in it } } + assertFalse("ses_1" in manager.activity.value) + } + + @Test + fun `global error without session is ignored`() = runBlocking { + directories["ses_1"] = "/repo/wt" + start() + + events.emit(ChatEventDto.Error(null)) + events.emit(ChatEventDto.QuestionAsked("ses_1", question("q_1", "ses_1"))) + + val snap = await("ses_1", SessionActivityKindDto.QUESTION) + assertEquals(1, snap.size) + } + @Test fun `unknown session directory is omitted`() = runBlocking { directories["ses_known"] = "/repo/wt" diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt index bbf25fd8c03e..2f3b9aa35917 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt @@ -12,7 +12,9 @@ import ai.kilocode.client.agentManager.SidePanelMode import ai.kilocode.client.agentManager.applySidePanelMode import ai.kilocode.client.agentManager.worktree.WorktreeController import ai.kilocode.client.agentManager.AgentManagerPanel +import ai.kilocode.client.agentManager.sessionAttentionNeeded import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.ui.AttentionDotIcon import ai.kilocode.log.KiloLog import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager @@ -32,6 +34,7 @@ import com.intellij.ui.content.ContentManagerListener import com.intellij.ui.content.ContentFactory import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.awt.BorderLayout @@ -132,6 +135,7 @@ internal class KiloToolWindowSetupService( val agentContent = factory.createContent(agent, KiloBundle.message("sidePanel.mode.agentManager"), false) agentContent.applySidePanelMode(SidePanelMode.AGENT_MANAGER) agentContent.setPreferredFocusedComponent { agentManagerPanel.component } + agentContent.putUserData(ToolWindow.SHOW_CONTENT_ICON, true) toolWindow.contentManager.addContent(chatContent) toolWindow.contentManager.addContent(agentContent) val listener = object : ContentManagerListener { @@ -146,6 +150,16 @@ internal class KiloToolWindowSetupService( toolWindow.contentManager.setSelectedContent(chatContent) manager.newSession() + // Show a notification dot on the Agents tab whenever a worktree session needs attention. + val dot = cs.launch { + project.service().activity.map(::sessionAttentionNeeded).collect { needed -> + withContext(Dispatchers.Main) { + agentContent.icon = if (needed) AttentionDotIcon else null + } + } + } + Disposer.register(manager) { dot.cancel() } + val actions = listOfNotNull( ActionManager.getInstance().getAction("Kilo.NewSession"), ActionManager.getInstance().getAction("Kilo.NewWorktree"), diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentAttention.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentAttention.kt new file mode 100644 index 000000000000..b4506b00801f --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentAttention.kt @@ -0,0 +1,16 @@ +package ai.kilocode.client.agentManager + +import ai.kilocode.rpc.dto.SessionActivityDto +import ai.kilocode.rpc.dto.SessionActivityKindDto + +/** + * Whether any session in the activity snapshot is waiting on the user or has failed, + * i.e. the Agents tab should show a notification dot. + */ +internal fun sessionAttentionNeeded(activity: Map): Boolean = + activity.values.any { + it.kind == SessionActivityKindDto.QUESTION || + it.kind == SessionActivityKindDto.PLAN || + it.kind == SessionActivityKindDto.PERMISSION || + it.kind == SessionActivityKindDto.ERROR + } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt index 0e561668a34f..5df656d7051f 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt @@ -24,12 +24,14 @@ private fun kind(kind: SessionActivityKindDto): SessionActivityKind = when (kind SessionActivityKindDto.QUESTION -> SessionActivityKind.QUESTION SessionActivityKindDto.PLAN -> SessionActivityKind.PLAN SessionActivityKindDto.PERMISSION -> SessionActivityKind.PERMISSION + SessionActivityKindDto.ERROR -> SessionActivityKind.ERROR } private fun rank(kind: SessionActivityKind): Int = when (kind) { SessionActivityKind.PERMISSION -> 0 SessionActivityKind.QUESTION -> 1 SessionActivityKind.PLAN -> 2 - SessionActivityKind.RUNNING -> 3 - SessionActivityKind.LOGIN_REQUIRED -> 4 + SessionActivityKind.ERROR -> 3 + SessionActivityKind.RUNNING -> 4 + SessionActivityKind.LOGIN_REQUIRED -> 5 } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt index af1b3ca7dbaf..750f65baad9d 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt @@ -3,23 +3,16 @@ package ai.kilocode.client.agentManager.worktree import ai.kilocode.client.session.SessionActivityKind import com.intellij.openapi.util.IconLoader import com.intellij.ui.AnimatedIcon -import com.intellij.util.IconUtil import javax.swing.Icon internal object WorktreeIcons { val branch: Icon = IconLoader.getIcon("/icons/worktreeBranch.svg", WorktreeIcons::class.java) val locked: Icon = IconLoader.getIcon("/icons/worktreeLock.svg", WorktreeIcons::class.java) - val running: Icon = IconLoader.getIcon("/icons/worktreeRunning.svg", WorktreeIcons::class.java) - private val prompt: Icon = IconLoader.getIcon("/icons/scroll-question.svg", WorktreeIcons::class.java) - val question: Icon = IconUtil.scale(prompt, null, branch.iconWidth.toFloat() / prompt.iconWidth.toFloat()) val spinner: Icon = AnimatedIcon.Default.INSTANCE fun forRow(locked: Boolean, pending: Boolean, kind: SessionActivityKind? = null): Icon = when { pending -> spinner - kind == SessionActivityKind.RUNNING -> running - kind == SessionActivityKind.QUESTION || - kind == SessionActivityKind.PLAN || - kind == SessionActivityKind.PERMISSION -> question + kind != null -> kind.icon() locked -> this.locked else -> branch } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ActivityIcon.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ActivityIcon.kt new file mode 100644 index 000000000000..32faafd079eb --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ActivityIcon.kt @@ -0,0 +1,64 @@ +package ai.kilocode.client.session + +import ai.kilocode.client.ui.UiStyle +import com.intellij.util.ui.JBFont +import com.intellij.util.ui.JBUI +import java.awt.Component +import java.awt.Graphics +import java.awt.Graphics2D +import java.awt.RenderingHints +import java.awt.geom.Ellipse2D +import javax.swing.Icon + +internal class ActivityIcon private constructor( + private val kind: SessionActivityKind, +) : Icon { + override fun getIconWidth() = JBUI.scale(16) + + override fun getIconHeight() = JBUI.scale(16) + + override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) { + val g2 = g.create() as Graphics2D + try { + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g2.translate(x, y) + g2.color = kind.style().bg() + val inset = JBUI.scale(1).toFloat() + val size = iconWidth - inset * 2 + g2.fill(Ellipse2D.Float(inset, inset, size, size)) + g2.color = kind.style().fg() + when (kind) { + SessionActivityKind.RUNNING -> paintDots(g2) + SessionActivityKind.ERROR -> paintText(g2, "!") + SessionActivityKind.LOGIN_REQUIRED, + SessionActivityKind.PERMISSION, + SessionActivityKind.PLAN, + SessionActivityKind.QUESTION -> paintText(g2, "?") + } + } finally { + g2.dispose() + } + } + + private fun paintDots(g2: Graphics2D) { + val dot = JBUI.scale(2.4f) + val y = iconHeight / 2f - dot / 2f + for (x in listOf(4.8f, 8f, 11.2f).map { JBUI.scale(it) - dot / 2f }) { + g2.fill(Ellipse2D.Float(x, y, dot, dot)) + } + } + + private fun paintText(g2: Graphics2D, text: String) { + g2.font = JBFont.small().asBold() + val fm = g2.fontMetrics + val width = fm.stringWidth(text) + val base = (iconHeight + fm.ascent - fm.descent) / 2 + g2.drawString(text, (iconWidth - width) / 2, base) + } + + companion object { + private val icons = SessionActivityKind.entries.associateWith { ActivityIcon(it) } + + fun of(kind: SessionActivityKind): Icon = icons.getValue(kind) + } +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionActivityKind.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionActivityKind.kt index 30869a4db221..d82dae0e3bd4 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionActivityKind.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionActivityKind.kt @@ -2,6 +2,7 @@ package ai.kilocode.client.session import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.ui.UiStyle +import javax.swing.Icon enum class SessionActivityKind { RUNNING, @@ -9,6 +10,7 @@ enum class SessionActivityKind { PERMISSION, PLAN, QUESTION, + ERROR, ; fun label(): String = when (this) { @@ -17,10 +19,14 @@ enum class SessionActivityKind { PERMISSION -> KiloBundle.message("history.badge.permission") PLAN -> KiloBundle.message("history.badge.plan") QUESTION -> KiloBundle.message("history.badge.question") + ERROR -> KiloBundle.message("history.badge.error") } fun style(): UiStyle.Badge.Style = when (this) { - RUNNING -> UiStyle.Badge.SessionRunning - LOGIN_REQUIRED, PERMISSION, PLAN, QUESTION -> UiStyle.Badge.Primary + RUNNING -> UiStyle.Badge.ActivityRunning + LOGIN_REQUIRED, PERMISSION, PLAN, QUESTION -> UiStyle.Badge.ActivityAttention + ERROR -> UiStyle.Badge.ActivityError } + + fun icon(): Icon = ActivityIcon.of(this) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/AttentionDotIcon.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/AttentionDotIcon.kt new file mode 100644 index 000000000000..2d14309f94c5 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/AttentionDotIcon.kt @@ -0,0 +1,27 @@ +package ai.kilocode.client.ui + +import com.intellij.util.ui.JBUI +import java.awt.Component +import java.awt.Graphics +import java.awt.Graphics2D +import java.awt.RenderingHints +import java.awt.geom.Ellipse2D +import javax.swing.Icon + +internal object AttentionDotIcon : Icon { + override fun getIconWidth() = JBUI.scale(8) + + override fun getIconHeight() = JBUI.scale(8) + + override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) { + val g2 = g.create() as Graphics2D + try { + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g2.translate(x, y) + g2.color = UiStyle.Badge.ActivityAttention.bg() + g2.fill(Ellipse2D.Float(0f, 0f, iconWidth.toFloat(), iconHeight.toFloat())) + } finally { + g2.dispose() + } + } +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt index a1a90e498e7d..34c89650b603 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt @@ -108,14 +108,38 @@ object UiStyle { ) } - object SessionRunning : Style { + object ActivityRunning : Style { override fun bg(): Color = JBColor.namedColor( - "Kilo.SessionStatus.runningBadgeBackground", - JBColor(Color(0xF9, 0x73, 0x16), Color(0xC2, 0x41, 0x0C)), + "Kilo.Activity.runningBackground", + JBColor(Color(0x55, 0xA7, 0x6A), Color(0x57, 0x96, 0x5C)), ) override fun fg(): Color = JBColor.namedColor( - "Kilo.SessionStatus.runningBadgeForeground", + "Kilo.Activity.runningForeground", + Color.WHITE, + ) + } + + object ActivityAttention : Style { + override fun bg(): Color = JBColor.namedColor( + "Kilo.Activity.attentionBackground", + JBColor(Color(0xE6, 0x6D, 0x17), Color(0xC7, 0x7D, 0x55)), + ) + + override fun fg(): Color = JBColor.namedColor( + "Kilo.Activity.attentionForeground", + Color.WHITE, + ) + } + + object ActivityError : Style { + override fun bg(): Color = JBColor.namedColor( + "Kilo.Activity.errorBackground", + JBColor(Color(0xE5, 0x57, 0x65), Color(0xDB, 0x5C, 0x5C)), + ) + + override fun fg(): Color = JBColor.namedColor( + "Kilo.Activity.errorForeground", Color.WHITE, ) } diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning.svg deleted file mode 100644 index cba67f6b29a3..000000000000 --- a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning_dark.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning_dark.svg deleted file mode 100644 index 600330d6e209..000000000000 --- a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeRunning_dark.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties index 46c9a429c6cc..68bc08f8a730 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties @@ -324,6 +324,7 @@ history.badge.loginRequired=Login Required history.badge.permission=Permission history.badge.plan=Plan history.badge.question=Question +history.badge.error=Error history.group.today=Today history.group.yesterday=Yesterday history.group.week=This Week diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentAttentionTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentAttentionTest.kt new file mode 100644 index 000000000000..e105475abc15 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentAttentionTest.kt @@ -0,0 +1,27 @@ +package ai.kilocode.client.agentManager + +import ai.kilocode.rpc.dto.SessionActivityDto +import ai.kilocode.rpc.dto.SessionActivityKindDto +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class AgentAttentionTest { + @Test + fun `attention states light up the dot`() { + for (kind in listOf( + SessionActivityKindDto.QUESTION, + SessionActivityKindDto.PLAN, + SessionActivityKindDto.PERMISSION, + SessionActivityKindDto.ERROR, + )) { + assertTrue(sessionAttentionNeeded(mapOf("ses" to SessionActivityDto("/repo/wt", kind))), kind.name) + } + } + + @Test + fun `running and empty do not light up the dot`() { + assertFalse(sessionAttentionNeeded(emptyMap())) + assertFalse(sessionAttentionNeeded(mapOf("ses" to SessionActivityDto("/repo/wt", SessionActivityKindDto.RUNNING)))) + } +} diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index 3a5c21ef1d4e..5eb350acf3ad 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -13,6 +13,7 @@ import ai.kilocode.client.agentManager.worktree.WorktreeStatusService import ai.kilocode.client.agentManager.worktree.ensureWorktreeSessionEditorKind import ai.kilocode.client.agentManager.worktree.worktreeSessionParams import ai.kilocode.client.diff.KiloDiffEditorKind +import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.client.testing.FakeWorktreeRpcApi import ai.kilocode.client.testing.TestCoroutines import ai.kilocode.client.testing.pumpEdt @@ -448,10 +449,24 @@ class AgentManagerPanelTest : BasePlatformTestCase() { flush() val row = row(panel, 0) - assertSame(WorktreeIcons.question, row.icon) + assertSame(SessionActivityKind.QUESTION.icon(), row.icon) assertEquals(emptyList(), row.badges) } + fun `test worktree row shows error activity icon`() { + val item = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") + val activity = MutableStateFlow(mapOf( + "ses_1" to SessionActivityDto(item.path, SessionActivityKindDto.ERROR), + )) + rpc.listed += item + val controller = WorktreeController(service, "/test", coroutines.scope, activity = activity) + val panel = edt { AgentManagerPanel(testRootDisposable, controller) } + edt { controller.reload() } + flush() + + assertSame(SessionActivityKind.ERROR.icon(), row(panel, 0).icon) + } + fun `test worktree row shows metrics from status service`() { val item = WorktreeDto("${project.basePath!!}/.kilo/worktrees/feature-x", "feature-x", "feature/x", "${project.basePath!!}/.kilo/worktrees/feature-x") rpc.listed += item diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt index 138fd8418d8a..57d91132699f 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt @@ -355,20 +355,20 @@ class WorktreeControllerTest : BasePlatformTestCase() { WorktreeIcons.forRow(locked = false, pending = true, kind = SessionActivityKind.RUNNING), ) assertSame( - WorktreeIcons.running, + SessionActivityKind.RUNNING.icon(), WorktreeIcons.forRow(locked = true, pending = false, kind = SessionActivityKind.RUNNING), ) assertSame( - WorktreeIcons.question, + SessionActivityKind.QUESTION.icon(), WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.QUESTION), ) assertSame( - WorktreeIcons.question, + SessionActivityKind.PLAN.icon(), WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.PLAN), ) assertSame( - WorktreeIcons.question, - WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.PERMISSION), + SessionActivityKind.ERROR.icon(), + WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.ERROR), ) assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(locked = true, pending = false)) assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(locked = false, pending = false)) @@ -377,14 +377,17 @@ class WorktreeControllerTest : BasePlatformTestCase() { fun `test worktree icons load at the same size`() { assertTrue("branch icon should load", WorktreeIcons.branch.iconWidth > 0) assertTrue("lock icon should load", WorktreeIcons.locked.iconWidth > 0) - assertTrue("running icon should load", WorktreeIcons.running.iconWidth > 0) - assertTrue("question icon should load", WorktreeIcons.question.iconWidth > 0) assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.locked.iconWidth) assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.locked.iconHeight) - assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.running.iconWidth) - assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.running.iconHeight) - assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.question.iconWidth) - assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.question.iconHeight) + for (kind in SessionActivityKind.entries) { + assertEquals(WorktreeIcons.branch.iconWidth, kind.icon().iconWidth) + assertEquals(WorktreeIcons.branch.iconHeight, kind.icon().iconHeight) + } + } + + fun `test activity icons are stable per kind`() { + assertSame(SessionActivityKind.RUNNING.icon(), SessionActivityKind.RUNNING.icon()) + assertNotSame(SessionActivityKind.RUNNING.icon(), SessionActivityKind.ERROR.icon()) } fun `test worktree delete eligibility excludes missing main and pending rows`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt index d5b365b95518..8b88c1b358ff 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt @@ -31,6 +31,21 @@ class WorktreeActivityTest { assertEquals(SessionActivityKind.QUESTION, result["/repo/b"]) } + @Test + fun `error outranks running but yields to interactive prompts`() { + val errorOverRunning = aggregateWorktreeActivity(mapOf( + "ses_run" to SessionActivityDto("/repo/wt", SessionActivityKindDto.RUNNING), + "ses_error" to SessionActivityDto("/repo/wt", SessionActivityKindDto.ERROR), + )) + assertEquals(SessionActivityKind.ERROR, errorOverRunning["/repo/wt"]) + + val questionOverError = aggregateWorktreeActivity(mapOf( + "ses_error" to SessionActivityDto("/repo/wt", SessionActivityKindDto.ERROR), + "ses_question" to SessionActivityDto("/repo/wt", SessionActivityKindDto.QUESTION), + )) + assertEquals(SessionActivityKind.QUESTION, questionOverError["/repo/wt"]) + } + @Test fun `normalizes trailing slashes`() { val result = aggregateWorktreeActivity(mapOf( diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt index e2710a9867aa..f0f826d95f50 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt @@ -50,11 +50,12 @@ class UiStyleTest : BasePlatformTestCase() { } fun `test session status badges use shared styles`() { - assertSame(UiStyle.Badge.SessionRunning, SessionActivityKind.RUNNING.style()) - assertSame(UiStyle.Badge.Primary, SessionActivityKind.QUESTION.style()) - assertSame(UiStyle.Badge.Primary, SessionActivityKind.PLAN.style()) - assertSame(UiStyle.Badge.Primary, SessionActivityKind.PERMISSION.style()) - assertSame(UiStyle.Badge.Primary, SessionActivityKind.LOGIN_REQUIRED.style()) + assertSame(UiStyle.Badge.ActivityRunning, SessionActivityKind.RUNNING.style()) + assertSame(UiStyle.Badge.ActivityAttention, SessionActivityKind.QUESTION.style()) + assertSame(UiStyle.Badge.ActivityAttention, SessionActivityKind.PLAN.style()) + assertSame(UiStyle.Badge.ActivityAttention, SessionActivityKind.PERMISSION.style()) + assertSame(UiStyle.Badge.ActivityAttention, SessionActivityKind.LOGIN_REQUIRED.style()) + assertSame(UiStyle.Badge.ActivityError, SessionActivityKind.ERROR.style()) } fun `test pull request states use github badge styles`() { diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/SessionDto.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/SessionDto.kt index c8058d5b4086..92f2eccf2241 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/SessionDto.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/SessionDto.kt @@ -53,6 +53,7 @@ enum class SessionActivityKindDto { QUESTION, PLAN, PERMISSION, + ERROR, } @Serializable From d5ddc8a34246042c6a70ca0f34d10f9330a3f69c Mon Sep 17 00:00:00 2001 From: kirillk Date: Thu, 20 Aug 2026 10:47:34 -0400 Subject: [PATCH 05/30] feat(jetbrains): animate running session icon in agent manager tree Replace the static running badge in the Agent Manager worktree list with an animated spinner that mirrors the VS Code Spinner: a 4x4 grid of rounded squares pulsing their opacity in the amber running brand color. Built as a frame-based AnimatedIcon so it animates via the list's ANIMATION_IN_RENDERER_ALLOWED flag with no extra wiring. --- .../agentManager/worktree/WorktreeIcons.kt | 6 ++ .../ai/kilocode/client/session/SpinnerIcon.kt | 93 +++++++++++++++++++ .../client/agentManager/WorktreeIconsTest.kt | 34 +++++++ 3 files changed, 133 insertions(+) create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt create mode 100644 packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt index 750f65baad9d..bf553f811a3c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt @@ -1,6 +1,7 @@ package ai.kilocode.client.agentManager.worktree import ai.kilocode.client.session.SessionActivityKind +import ai.kilocode.client.session.SpinnerIcon import com.intellij.openapi.util.IconLoader import com.intellij.ui.AnimatedIcon import javax.swing.Icon @@ -10,8 +11,13 @@ internal object WorktreeIcons { val locked: Icon = IconLoader.getIcon("/icons/worktreeLock.svg", WorktreeIcons::class.java) val spinner: Icon = AnimatedIcon.Default.INSTANCE + // Single swap point for the running-session icon. Change this to retarget the animation + // (e.g. AnimatedIcon.Default.INSTANCE or SessionActivityKind.RUNNING.icon()). + val running: Icon = SpinnerIcon.icon + fun forRow(locked: Boolean, pending: Boolean, kind: SessionActivityKind? = null): Icon = when { pending -> spinner + kind == SessionActivityKind.RUNNING -> running kind != null -> kind.icon() locked -> this.locked else -> branch diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt new file mode 100644 index 000000000000..66d5c5021502 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt @@ -0,0 +1,93 @@ +package ai.kilocode.client.session + +import ai.kilocode.client.ui.UiStyle +import com.intellij.ui.AnimatedIcon +import com.intellij.ui.ColorUtil +import com.intellij.util.ui.JBUI +import java.awt.Component +import java.awt.Graphics +import java.awt.Graphics2D +import java.awt.RenderingHints +import java.awt.geom.RoundRectangle2D +import javax.swing.Icon +import kotlin.math.cos + +/** + * Animated running badge that mirrors the VS Code Agent Manager spinner: a 4x4 grid of rounded + * squares whose opacity pulses. Corners stay empty; the inner squares pulse brighter than the + * outer ring. Rendered in the amber "running" brand color ([UiStyle.Badge.ActivityRunning]). + * + * Built as a frame-based [com.intellij.ui.AnimatedIcon] so it animates automatically inside list + * cell renderers that set `AnimatedIcon.ANIMATION_IN_RENDERER_ALLOWED` (see `ActiveListView`). + */ +internal object SpinnerIcon { + private const val GRID = 4 + private const val COUNT = GRID * GRID + + // VS Code viewBox is 15 units: squares sit on a 4-unit pitch and are 3 units wide with a 1-unit + // corner radius. We map those units onto a scaled 16px icon. + private const val VIEWBOX = 15f + private const val PITCH = 4f + private const val SQUARE = 3f + private const val RADIUS = 1f + + private const val FRAMES = 12 + private const val CYCLE_MS = 1200 + private val DELAY = CYCLE_MS / FRAMES + + // Corners read as noise at this size, so VS Code hides them. + private val CORNERS = setOf(0, 3, 12, 15) + private val INNER = setOf(5, 6, 9, 10) + + // Opacity range per group (VS Code: inner 0.4..1.0, outer ring 0.15..0.35). + private const val INNER_LO = 0.4f + private const val INNER_HI = 1.0f + private const val OUTER_LO = 0.15f + private const val OUTER_HI = 0.35f + + // Deterministic per-square phase (0..1) that scatters the pulse like VS Code's randomized delays. + private val PHASE = floatArrayOf( + 0.00f, 0.15f, 0.62f, 0.00f, + 0.40f, 0.85f, 0.25f, 0.70f, + 0.10f, 0.55f, 0.30f, 0.90f, + 0.00f, 0.48f, 0.78f, 0.00f, + ) + + val icon: Icon = AnimatedIcon(DELAY, *Array(FRAMES) { Frame(it) }) + + /** Ease-in-out 0..1..0 wave, matching CSS `ease-in-out` opacity pulses. */ + private fun ease(t: Float): Float = ((1f - cos(2.0 * Math.PI * t)) / 2.0).toFloat() + + private fun opacity(index: Int, frame: Int): Float { + val lo = if (index in INNER) INNER_LO else OUTER_LO + val hi = if (index in INNER) INNER_HI else OUTER_HI + return lo + (hi - lo) * ease(PHASE[index] + frame.toFloat() / FRAMES) + } + + private class Frame(private val frame: Int) : Icon { + override fun getIconWidth() = JBUI.scale(16) + + override fun getIconHeight() = JBUI.scale(16) + + override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) { + val g2 = g.create() as Graphics2D + try { + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g2.translate(x, y) + val scale = iconWidth / VIEWBOX + val size = SQUARE * scale + val arc = RADIUS * 2f * scale + val base = UiStyle.Badge.ActivityRunning.fg() + for (i in 0 until COUNT) { + if (i in CORNERS) continue + g2.color = ColorUtil.withAlpha(base, opacity(i, frame).toDouble()) + val px = (i % GRID) * PITCH * scale + val py = (i / GRID) * PITCH * scale + g2.fill(RoundRectangle2D.Float(px, py, size, size, arc, arc)) + } + } finally { + g2.dispose() + } + } + } +} diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt new file mode 100644 index 000000000000..50c044f09e3a --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt @@ -0,0 +1,34 @@ +package ai.kilocode.client.agentManager + +import ai.kilocode.client.agentManager.worktree.WorktreeIcons +import ai.kilocode.client.session.SessionActivityKind +import com.intellij.testFramework.fixtures.BasePlatformTestCase +import com.intellij.ui.AnimatedIcon +import com.intellij.util.ui.JBUI + +class WorktreeIconsTest : BasePlatformTestCase() { + fun `test running session resolves to the animated spinner`() { + assertSame(WorktreeIcons.running, WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.RUNNING)) + } + + fun `test running icon is animated and sized to the row icon`() { + assertTrue(WorktreeIcons.running is AnimatedIcon) + assertEquals(JBUI.scale(16), WorktreeIcons.running.iconWidth) + assertEquals(JBUI.scale(16), WorktreeIcons.running.iconHeight) + } + + fun `test pending outranks running and uses the platform spinner`() { + assertSame(WorktreeIcons.spinner, WorktreeIcons.forRow(locked = false, pending = true, kind = SessionActivityKind.RUNNING)) + } + + fun `test non-running kinds keep the activity badge`() { + val error = WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.ERROR) + assertSame(SessionActivityKind.ERROR.icon(), error) + assertNotSame(WorktreeIcons.running, error) + } + + fun `test locked and plain rows keep their static icons`() { + assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(locked = true, pending = false, kind = null)) + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(locked = false, pending = false, kind = null)) + } +} From ac98f5c77460d9627ccc3e6b1a9bc09bfd327bb3 Mon Sep 17 00:00:00 2001 From: kirillk Date: Thu, 20 Aug 2026 14:40:27 -0400 Subject: [PATCH 06/30] fix(jetbrains): refine agent manager activity icons --- .../jetbrains-agent-manager-activity-icons.md | 5 +++ .../client/agentManager/AgentManagerPanel.kt | 2 +- .../agentManager/worktree/WorktreeActivity.kt | 5 --- .../agentManager/worktree/WorktreeIcons.kt | 26 ++++++++++---- .../worktree/WorktreeSessionEditorPanel.kt | 3 +- .../ai/kilocode/client/session/IdleIcon.kt | 36 +++++++++++++++++++ .../agentManager/AgentManagerPanelTest.kt | 4 +-- .../agentManager/WorktreeControllerTest.kt | 20 +++++------ .../client/agentManager/WorktreeIconsTest.kt | 23 +++++++----- .../worktree/WorktreeActivityTest.kt | 8 ----- .../WorktreeSessionEditorPanelTest.kt | 6 ++-- 11 files changed, 90 insertions(+), 48 deletions(-) create mode 100644 .changeset/jetbrains-agent-manager-activity-icons.md create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/IdleIcon.kt diff --git a/.changeset/jetbrains-agent-manager-activity-icons.md b/.changeset/jetbrains-agent-manager-activity-icons.md new file mode 100644 index 000000000000..38244d19927a --- /dev/null +++ b/.changeset/jetbrains-agent-manager-activity-icons.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Show compact Agent Manager activity icons for running and waiting sessions while keeping idle rows aligned with a smaller idle dot. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 9b16a8fcf961..0ae909e4d03e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -488,7 +488,7 @@ class AgentManagerPanel( override val title: String get() = if (current) dto.branch else WorktreeTitle.text(dto.name, dto.path, pr) override val description: String get() = WorktreeTitle.fallback(dto.path) override val tooltip: String? get() = null - override val icon = WorktreeIcons.forRow(dto.locked, pending, kind) + override val icon = WorktreeIcons.forRow(pending, kind) override val section: String? get() = if (current) null else KiloBundle.message("worktree.section.local") override val search: String get() = listOfNotNull(dto.name, dto.branch, dto.path, dto.lockReason).joinToString(" ") private val customName: String? get() = WorktreeTitle.custom(dto.name, dto.path) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt index 5df656d7051f..8422c556bf2c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt @@ -1,7 +1,6 @@ package ai.kilocode.client.agentManager.worktree import ai.kilocode.client.session.SessionActivityKind -import ai.kilocode.client.ui.list.ActiveListBadge import ai.kilocode.rpc.dto.SessionActivityDto import ai.kilocode.rpc.dto.SessionActivityKindDto @@ -11,10 +10,6 @@ internal fun aggregateWorktreeActivity( .groupBy { normalize(it.directory) } .mapValues { (_, items) -> items.map { kind(it.kind) }.minBy(::rank) } -internal fun worktreeActivityBadge(kind: SessionActivityKind): ActiveListBadge { - return ActiveListBadge(kind.label(), kind.style()) -} - internal fun normalizeWorktreePath(path: String): String = normalize(path) private fun normalize(path: String): String = path.trimEnd('/') diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt index bf553f811a3c..36e81fa935dc 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt @@ -1,5 +1,6 @@ package ai.kilocode.client.agentManager.worktree +import ai.kilocode.client.session.IdleIcon import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.client.session.SpinnerIcon import com.intellij.openapi.util.IconLoader @@ -15,11 +16,24 @@ internal object WorktreeIcons { // (e.g. AnimatedIcon.Default.INSTANCE or SessionActivityKind.RUNNING.icon()). val running: Icon = SpinnerIcon.icon - fun forRow(locked: Boolean, pending: Boolean, kind: SessionActivityKind? = null): Icon = when { - pending -> spinner - kind == SessionActivityKind.RUNNING -> running - kind != null -> kind.icon() - locked -> this.locked - else -> branch + // Small muted dot the size of the status icons. An idle row keeps the same leading slot so the + // title never shifts, but the dot reads as quieter and smaller than the running/question glyphs. + val idle: Icon = IdleIcon + + // A worktree row shows the running spinner or the "?" attention glyph while a session there is + // active; idle, locked, and errored rows fall back to the small [idle] dot. [pending] (creation + // in progress) still shows the platform spinner. + fun forRow(pending: Boolean, kind: SessionActivityKind? = null): Icon = + if (pending) spinner else forKind(kind) + + // Status icon for a single session: the spinner while running, the "?" attention glyph while + // waiting for input, and the small [idle] dot otherwise. + fun forKind(kind: SessionActivityKind?): Icon = when (kind) { + SessionActivityKind.RUNNING -> running + SessionActivityKind.QUESTION, + SessionActivityKind.PERMISSION, + SessionActivityKind.PLAN, + SessionActivityKind.LOGIN_REQUIRED -> kind.icon() + SessionActivityKind.ERROR, null -> idle } } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt index 3fd5747820ad..18cd2bf159aa 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt @@ -14,7 +14,6 @@ import ai.kilocode.client.session.history.LocalHistoryItem import ai.kilocode.client.plugin.KiloPluginSettings import ai.kilocode.client.telemetry.Telemetry import ai.kilocode.client.ui.list.ActiveList -import ai.kilocode.client.ui.list.ActiveListBadge import ai.kilocode.client.ui.list.ActiveListConfig import ai.kilocode.client.ui.list.ActiveListDeleteOptions import ai.kilocode.client.ui.list.ActiveListEditOptions @@ -576,7 +575,7 @@ class WorktreeSessionEditorPanel( return name } override val tooltip: String get() = title - override val badges: List get() = listOfNotNull(kind?.let(::worktreeActivityBadge)) + override val icon: Icon? get() = WorktreeIcons.forKind(kind) override val section: String get() = HistoryTime.title(HistoryTime.section(item)) override val search: String get() = listOf(session.title, session.id, session.directory).joinToString(" ") } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/IdleIcon.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/IdleIcon.kt new file mode 100644 index 000000000000..43ae74c2e5a6 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/IdleIcon.kt @@ -0,0 +1,36 @@ +package ai.kilocode.client.session + +import com.intellij.util.ui.JBUI +import com.intellij.util.ui.NamedColorUtil +import java.awt.Component +import java.awt.Graphics +import java.awt.Graphics2D +import java.awt.RenderingHints +import java.awt.geom.Ellipse2D +import javax.swing.Icon + +/** + * Idle-status glyph: a small muted dot centered in the same 16x16 bounds the running and + * question icons use. Keeping the bounds identical stops the row title from shifting when a + * session goes active or idle, while the deliberately smaller dot reads as quieter than the + * larger running/question glyphs that fill the icon. + */ +internal object IdleIcon : Icon { + override fun getIconWidth() = JBUI.scale(16) + + override fun getIconHeight() = JBUI.scale(16) + + override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) { + val g2 = g.create() as Graphics2D + try { + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g2.translate(x, y) + g2.color = NamedColorUtil.getInactiveTextColor() + val dot = JBUI.scale(6).toFloat() + val origin = (iconWidth - dot) / 2f + g2.fill(Ellipse2D.Float(origin, origin, dot, dot)) + } finally { + g2.dispose() + } + } +} diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index 5eb350acf3ad..6ddf7af5d502 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -453,7 +453,7 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(emptyList(), row.badges) } - fun `test worktree row shows error activity icon`() { + fun `test worktree row uses the idle dot for error activity`() { val item = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") val activity = MutableStateFlow(mapOf( "ses_1" to SessionActivityDto(item.path, SessionActivityKindDto.ERROR), @@ -464,7 +464,7 @@ class AgentManagerPanelTest : BasePlatformTestCase() { edt { controller.reload() } flush() - assertSame(SessionActivityKind.ERROR.icon(), row(panel, 0).icon) + assertSame(WorktreeIcons.idle, row(panel, 0).icon) } fun `test worktree row shows metrics from status service`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt index 57d91132699f..176a4e8579da 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt @@ -349,29 +349,25 @@ class WorktreeControllerTest : BasePlatformTestCase() { } } - fun `test worktree icons prefer pending then activity then locked then branch`() { + fun `test worktree row icons show only while running or waiting`() { assertSame( WorktreeIcons.spinner, - WorktreeIcons.forRow(locked = false, pending = true, kind = SessionActivityKind.RUNNING), + WorktreeIcons.forRow(pending = true, kind = SessionActivityKind.RUNNING), ) assertSame( - SessionActivityKind.RUNNING.icon(), - WorktreeIcons.forRow(locked = true, pending = false, kind = SessionActivityKind.RUNNING), + WorktreeIcons.running, + WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.RUNNING), ) assertSame( SessionActivityKind.QUESTION.icon(), - WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.QUESTION), + WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.QUESTION), ) assertSame( SessionActivityKind.PLAN.icon(), - WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.PLAN), + WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.PLAN), ) - assertSame( - SessionActivityKind.ERROR.icon(), - WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.ERROR), - ) - assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(locked = true, pending = false)) - assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(locked = false, pending = false)) + assertSame(WorktreeIcons.idle, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR)) + assertSame(WorktreeIcons.idle, WorktreeIcons.forRow(pending = false, kind = null)) } fun `test worktree icons load at the same size`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt index 50c044f09e3a..e272137d6253 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt @@ -8,7 +8,7 @@ import com.intellij.util.ui.JBUI class WorktreeIconsTest : BasePlatformTestCase() { fun `test running session resolves to the animated spinner`() { - assertSame(WorktreeIcons.running, WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.RUNNING)) + assertSame(WorktreeIcons.running, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.RUNNING)) } fun `test running icon is animated and sized to the row icon`() { @@ -18,17 +18,22 @@ class WorktreeIconsTest : BasePlatformTestCase() { } fun `test pending outranks running and uses the platform spinner`() { - assertSame(WorktreeIcons.spinner, WorktreeIcons.forRow(locked = false, pending = true, kind = SessionActivityKind.RUNNING)) + assertSame(WorktreeIcons.spinner, WorktreeIcons.forRow(pending = true, kind = SessionActivityKind.RUNNING)) } - fun `test non-running kinds keep the activity badge`() { - val error = WorktreeIcons.forRow(locked = false, pending = false, kind = SessionActivityKind.ERROR) - assertSame(SessionActivityKind.ERROR.icon(), error) - assertNotSame(WorktreeIcons.running, error) + fun `test waiting kinds resolve to the attention glyph`() { + assertSame(SessionActivityKind.QUESTION.icon(), WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.QUESTION)) + assertSame(SessionActivityKind.PLAN.icon(), WorktreeIcons.forKind(SessionActivityKind.PLAN)) } - fun `test locked and plain rows keep their static icons`() { - assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(locked = true, pending = false, kind = null)) - assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(locked = false, pending = false, kind = null)) + fun `test idle and errored rows use the idle dot`() { + assertSame(WorktreeIcons.idle, WorktreeIcons.forRow(pending = false, kind = null)) + assertSame(WorktreeIcons.idle, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR)) + assertSame(WorktreeIcons.idle, WorktreeIcons.forKind(null)) + } + + fun `test idle dot matches the status icon size`() { + assertEquals(WorktreeIcons.running.iconWidth, WorktreeIcons.idle.iconWidth) + assertEquals(WorktreeIcons.running.iconHeight, WorktreeIcons.idle.iconHeight) } } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt index 8b88c1b358ff..02b4292854ed 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt @@ -55,12 +55,4 @@ class WorktreeActivityTest { assertEquals(mapOf("/repo/wt" to SessionActivityKind.RUNNING), result) assertEquals("/repo/wt", normalizeWorktreePath("/repo/wt/")) } - - @Test - fun `worktree activity badges use shared session activity styles`() { - assertEquals(SessionActivityKind.RUNNING.style(), worktreeActivityBadge(SessionActivityKind.RUNNING).style) - assertEquals(SessionActivityKind.QUESTION.style(), worktreeActivityBadge(SessionActivityKind.QUESTION).style) - assertEquals(SessionActivityKind.PERMISSION.style(), worktreeActivityBadge(SessionActivityKind.PERMISSION).style) - assertEquals(SessionActivityKind.RUNNING.label(), worktreeActivityBadge(SessionActivityKind.RUNNING).text) - } } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt index 49640d3ff32d..adc81218ec97 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt @@ -236,7 +236,7 @@ class WorktreeSessionEditorPanelTest : BasePlatformTestCase() { assertEquals("new", edt { (list.selectedValue as ActiveListItem).key }) } - fun `test session rows match history visuals`() { + fun `test running session row shows the activity icon and no badge`() { manager.kinds = mapOf("ses_1" to SessionActivityKind.RUNNING) val session = session("ses_1", nowSeconds()) rpc.listed += session @@ -246,9 +246,9 @@ class WorktreeSessionEditorPanelTest : BasePlatformTestCase() { val row = row("ses_1") assertEquals("Session ses_1", row.title) - assertNull(row.icon) + assertSame(WorktreeIcons.running, row.icon) assertNull(row.description) - assertEquals(listOf(ActiveListBadge(SessionActivityKind.RUNNING.label(), SessionActivityKind.RUNNING.style())), row.badges) + assertEquals(emptyList(), row.badges) assertNull(row.trailing) assertEquals(HistoryTime.title(HistoryTime.section(LocalHistoryItem(session))), row.section) } From 082b38b2349aaf5b02f22dadf4bec2eff228c4c0 Mon Sep 17 00:00:00 2001 From: kirillk Date: Thu, 20 Aug 2026 15:28:18 -0400 Subject: [PATCH 07/30] fix(jetbrains): stop session error card EDT freeze --- .../jetbrains-session-error-card-freeze.md | 5 + .../session/views/SessionOutcomeView.kt | 29 +---- .../session/views/SessionOutcomeViewTest.kt | 110 ++++++++++++++++++ 3 files changed, 118 insertions(+), 26 deletions(-) create mode 100644 .changeset/jetbrains-session-error-card-freeze.md diff --git a/.changeset/jetbrains-session-error-card-freeze.md b/.changeset/jetbrains-session-error-card-freeze.md new file mode 100644 index 000000000000..f269cf7e586f --- /dev/null +++ b/.changeset/jetbrains-session-error-card-freeze.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Fix an IDE freeze when a chat session reports an error, which could hang the whole IDE while opening a worktree session editor. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/views/SessionOutcomeView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/views/SessionOutcomeView.kt index 3d87c2c071a1..7e92be8a5101 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/views/SessionOutcomeView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/views/SessionOutcomeView.kt @@ -81,32 +81,10 @@ class SessionOutcomeView( } private class ErrorBody { + // The error text is a JViewport view. Never resize it from getPreferredSize(): + // JViewport listens for component-resized events and will feed them back into layout. private val area = object : JBTextArea() { - override fun getPreferredSize() = withWidth(super.getPreferredSize().height) - override fun scrollRectToVisible(aRect: Rectangle) {} - - private fun withWidth(fallback: Int): Dimension { - val w = availableWidth() - if (w <= 0) return Dimension(super.getPreferredSize().width, fallback) - val old = size - setSize(w, Int.MAX_VALUE) - val ps = super.getPreferredSize() - setSize(old) - return Dimension(w, ps.height) - } - - private fun availableWidth(): Int { - var node = parent - while (node != null) { - if (node.width > 0) { - val ins = node.insets - return (node.width - ins.left - ins.right).coerceAtLeast(0) - } - node = node.parent - } - return width - } }.apply { isEditable = false isOpaque = false @@ -124,8 +102,7 @@ private class ErrorBody { val ins = viewportBorder?.getBorderInsets(this) ?: JBUI.emptyInsets() val chrome = insets.top + insets.bottom + ins.top + ins.bottom + area.insets.top + area.insets.bottom val cap = area.getFontMetrics(area.font).height * SessionUiStyle.View.Outcome.ERROR_LINES + chrome - val height = minOf(area.preferredSize.height + chrome, cap) - return Dimension(size.width, height) + return Dimension(size.width, minOf(size.height, cap)) } override fun updateUI() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/views/SessionOutcomeViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/views/SessionOutcomeViewTest.kt index 01ed3a46fbda..b4266614f7ac 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/views/SessionOutcomeViewTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/views/SessionOutcomeViewTest.kt @@ -3,6 +3,7 @@ package ai.kilocode.client.session.views import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.session.model.Outcome import ai.kilocode.client.session.model.OutcomeTone +import ai.kilocode.client.session.ui.SessionLayout import ai.kilocode.client.session.ui.style.SessionEditorStyle import ai.kilocode.client.session.ui.style.SessionUiStyle import ai.kilocode.client.ui.UiStyle @@ -13,7 +14,11 @@ import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBTextArea import java.awt.Container +import java.awt.Dimension +import java.awt.event.ComponentAdapter +import java.awt.event.ComponentEvent import javax.swing.Icon +import javax.swing.JPanel import javax.swing.ScrollPaneConstants @Suppress("UnstableApiUsage") @@ -155,8 +160,113 @@ class SessionOutcomeViewTest : BasePlatformTestCase() { } } + fun `test realized error body preferred size does not resize text area`() { + edt { + val msg = "OpenRouter balance is too low. ".repeat(20) + val view = realized(msg) + val pane = errorScroll(view, msg) + val area = pane.viewport.view as JBTextArea + val size = Dimension(area.size) + + area.preferredSize + pane.preferredSize + + assertEquals(size, area.size) + } + } + + fun `test realized error body does not fire resize events while measuring`() { + edt { + val msg = "OpenRouter balance is too low. ".repeat(20) + val view = realized(msg) + val pane = errorScroll(view, msg) + val area = pane.viewport.view as JBTextArea + var count = 0 + area.addComponentListener(object : ComponentAdapter() { + override fun componentResized(e: ComponentEvent) { + count++ + } + }) + + repeat(4) { + area.preferredSize + pane.preferredSize + view.doLayout() + pane.doLayout() + pane.viewport.doLayout() + } + + assertEquals(0, count) + } + } + + fun `test realized error card caps height at five text lines`() { + edt { + val msg = (1..12).joinToString("\n") { idx -> "line $idx" } + val view = realized(msg) + val pane = errorScroll(view, msg) + val area = pane.viewport.view as JBTextArea + val line = area.getFontMetrics(area.font).height + val chrome = chrome(pane, area) + + assertEquals(line * SessionUiStyle.View.Outcome.ERROR_LINES + chrome, pane.height) + assertTrue(area.preferredSize.height > pane.viewport.extentSize.height) + } + } + + fun `test realized error card shrinks for short messages`() { + edt { + val msg = "line 1\nline 2" + val view = realized(msg) + val pane = errorScroll(view, msg) + val area = pane.viewport.view as JBTextArea + val chrome = chrome(pane, area) + + assertEquals(area.preferredSize.height + chrome, pane.height) + } + } + + fun `test long single-line error wraps at card width`() { + edt { + val msg = "OpenRouter balance is too low. ".repeat(20) + val view = realized(msg, 260, 600) + val pane = errorScroll(view, msg) + val area = pane.viewport.view as JBTextArea + val line = area.getFontMetrics(area.font).height + + assertTrue(area.preferredSize.height > line + area.insets.top + area.insets.bottom) + } + } + private fun findText(root: Container, text: String) = findAll(root).firstOrNull { it.text == text } + private fun realized(text: String, width: Int = 640, height: Int = 480): SessionOutcomeView { + val view = SessionOutcomeView() + view.showError(text, "APIError") + val root = JPanel(SessionLayout()) + root.setSize(width, height) + root.add(view) + root.addNotify() + repeat(4) { + layoutTree(root) + } + return view + } + + private fun layoutTree(root: Container) { + root.doLayout() + for (child in root.components) { + if (child is Container) layoutTree(child) + } + } + + private fun chrome(pane: JBScrollPane, area: JBTextArea): Int { + val border = pane.viewportBorder?.getBorderInsets(pane) + return pane.insets.top + pane.insets.bottom + + (border?.let { it.top + it.bottom } ?: 0) + + area.insets.top + area.insets.bottom + } + private fun headerBorder(root: SessionOutcomeView) = ((root.layout as java.awt.BorderLayout).getLayoutComponent(java.awt.BorderLayout.NORTH) as Container) .let { (it as javax.swing.JPanel).border.getBorderInsets(it) } From 0161c3a4baf1c710e96dc60de58927f629c940c5 Mon Sep 17 00:00:00 2001 From: kirillk Date: Thu, 20 Aug 2026 16:30:58 -0400 Subject: [PATCH 08/30] fix(jetbrains): refine agent manager badges --- .changeset/quiet-badges.md | 5 ++ .../client/agentManager/AgentManagerPanel.kt | 2 +- .../worktree/WorktreeSessionEditorPanel.kt | 7 ++- .../kotlin/ai/kilocode/client/ui/UiStyle.kt | 55 +++++++++---------- .../agentManager/AgentManagerPanelTest.kt | 22 +++++++- .../WorktreeSessionEditorPanelTest.kt | 20 +++++-- .../ai/kilocode/client/ui/UiStyleTest.kt | 14 +++++ 7 files changed, 90 insertions(+), 35 deletions(-) create mode 100644 .changeset/quiet-badges.md diff --git a/.changeset/quiet-badges.md b/.changeset/quiet-badges.md new file mode 100644 index 000000000000..0acc8443a9ce --- /dev/null +++ b/.changeset/quiet-badges.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Improve JetBrains Agent Manager session status badges, selection persistence, and PR badge theming. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 0ae909e4d03e..20b4007d0fe5 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -145,7 +145,7 @@ class AgentManagerPanel( } fun refresh() { - selected = currentEditorWorktree() + selected = selected ?: currentEditorWorktree() controller.reload() project?.service()?.refreshStats() project?.service()?.refreshPr() diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt index 18cd2bf159aa..779cec131fbd 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt @@ -14,6 +14,7 @@ import ai.kilocode.client.session.history.LocalHistoryItem import ai.kilocode.client.plugin.KiloPluginSettings import ai.kilocode.client.telemetry.Telemetry import ai.kilocode.client.ui.list.ActiveList +import ai.kilocode.client.ui.list.ActiveListBadge import ai.kilocode.client.ui.list.ActiveListConfig import ai.kilocode.client.ui.list.ActiveListDeleteOptions import ai.kilocode.client.ui.list.ActiveListEditOptions @@ -575,7 +576,11 @@ class WorktreeSessionEditorPanel( return name } override val tooltip: String get() = title - override val icon: Icon? get() = WorktreeIcons.forKind(kind) + override val badges: List + get() { + if (deleting) return emptyList() + return listOfNotNull(kind?.let { ActiveListBadge(it.label(), it.style()) }) + } override val section: String get() = HistoryTime.title(HistoryTime.section(item)) override val search: String get() = listOf(session.title, session.id, session.directory).joinToString(" ") } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt index 34c89650b603..2e2c9d687f7d 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt @@ -3,6 +3,7 @@ package ai.kilocode.client.ui import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorColorsScheme +import com.intellij.ui.ColorUtil import com.intellij.ui.JBColor import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI @@ -52,6 +53,8 @@ object UiStyle { /** Filled badge styles shared across JetBrains UI surfaces. */ object Badge { + private const val PR_SOFT_ALPHA = 0.15 + interface Style { fun bg(): Color @@ -145,51 +148,47 @@ object UiStyle { } object PullRequestOpen : Style { - override fun bg(): Color = JBColor.namedColor( - "Kilo.PullRequest.openBadgeBackground", - JBColor(Color(0x1F, 0x88, 0x3D), Color(0x23, 0x86, 0x36)), - ) - - override fun fg(): Color = JBColor.namedColor( + private val accent = JBColor.namedColor( "Kilo.PullRequest.openBadgeForeground", - Color.WHITE, + JBColor(Color(0x1A, 0x7F, 0x37), Color(0x3F, 0xB9, 0x50)), ) + + override fun bg(): Color = ColorUtil.withAlpha(accent, PR_SOFT_ALPHA) + + override fun fg(): Color = accent } object PullRequestDraft : Style { - override fun bg(): Color = JBColor.namedColor( - "Kilo.PullRequest.draftBadgeBackground", - JBColor(Color(0x6E, 0x77, 0x81), Color(0x6E, 0x76, 0x81)), - ) - - override fun fg(): Color = JBColor.namedColor( + private val accent = JBColor.namedColor( "Kilo.PullRequest.draftBadgeForeground", - Color.WHITE, + JBColor(Color(0x59, 0x63, 0x6E), Color(0x91, 0x98, 0xA1)), ) + + override fun bg(): Color = ColorUtil.withAlpha(accent, PR_SOFT_ALPHA) + + override fun fg(): Color = accent } object PullRequestMerged : Style { - override fun bg(): Color = JBColor.namedColor( - "Kilo.PullRequest.mergedBadgeBackground", - JBColor(Color(0x82, 0x50, 0xDF), Color(0x89, 0x57, 0xE5)), - ) - - override fun fg(): Color = JBColor.namedColor( + private val accent = JBColor.namedColor( "Kilo.PullRequest.mergedBadgeForeground", - Color.WHITE, + JBColor(Color(0x82, 0x50, 0xDF), Color(0xA3, 0x71, 0xF7)), ) + + override fun bg(): Color = ColorUtil.withAlpha(accent, PR_SOFT_ALPHA) + + override fun fg(): Color = accent } object PullRequestClosed : Style { - override fun bg(): Color = JBColor.namedColor( - "Kilo.PullRequest.closedBadgeBackground", - JBColor(Color(0xCF, 0x22, 0x2E), Color(0xDA, 0x36, 0x33)), - ) - - override fun fg(): Color = JBColor.namedColor( + private val accent = JBColor.namedColor( "Kilo.PullRequest.closedBadgeForeground", - Color.WHITE, + JBColor(Color(0xCF, 0x22, 0x2E), Color(0xF8, 0x51, 0x49)), ) + + override fun bg(): Color = ColorUtil.withAlpha(accent, PR_SOFT_ALPHA) + + override fun fg(): Color = accent } } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index 6ddf7af5d502..561d04b0d411 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -233,7 +233,7 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(second.id, edt { (list.selectedValue as ActiveListItem).key }) } - fun `test refresh selects active worktree editor`() { + fun `test refresh keeps existing selection`() { val first = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") val second = WorktreeDto("/repo/.kilo/worktrees/feature-y", "feature-y", "feature/y", "/repo/.kilo/worktrees/feature-y") rpc.listed += first @@ -251,6 +251,26 @@ class AgentManagerPanelTest : BasePlatformTestCase() { } flush() + assertEquals(first.id, edt { (list.selectedValue as ActiveListItem).key }) + } + + fun `test refresh uses active worktree editor when no selection exists`() { + val first = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") + val second = WorktreeDto("/repo/.kilo/worktrees/feature-y", "feature-y", "feature/y", "/repo/.kilo/worktrees/feature-y") + rpc.listed += first + rpc.listed += second + val controller = WorktreeController(service, "/test", coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + val list = edt { UIUtil.findComponentOfType(panel, JBList::class.java)!! } + edt { + ensureWorktreeSessionEditorKind() + project.service().open(WorktreeSessionEditorKind.ID, worktreeSessionParams(second), focus = true) + panel.refresh() + } + flush() + assertEquals(second.id, edt { (list.selectedValue as ActiveListItem).key }) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt index adc81218ec97..5541e47ae457 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt @@ -14,9 +14,9 @@ import ai.kilocode.client.testing.FakeSessionRpcApi import ai.kilocode.client.testing.TestCoroutines import ai.kilocode.client.testing.pumpEdt import ai.kilocode.client.testing.fire +import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.plugin.KiloPluginSettings import ai.kilocode.client.ui.list.ActiveList -import ai.kilocode.client.ui.list.ActiveListBadge import ai.kilocode.client.ui.list.ActiveListItem import ai.kilocode.client.ui.list.activeListSectionTitle import ai.kilocode.client.ui.list.activeListToolWindowBackground @@ -236,7 +236,7 @@ class WorktreeSessionEditorPanelTest : BasePlatformTestCase() { assertEquals("new", edt { (list.selectedValue as ActiveListItem).key }) } - fun `test running session row shows the activity icon and no badge`() { + fun `test running session row shows activity badge without leading icon`() { manager.kinds = mapOf("ses_1" to SessionActivityKind.RUNNING) val session = session("ses_1", nowSeconds()) rpc.listed += session @@ -246,13 +246,25 @@ class WorktreeSessionEditorPanelTest : BasePlatformTestCase() { val row = row("ses_1") assertEquals("Session ses_1", row.title) - assertSame(WorktreeIcons.running, row.icon) + assertNull(row.icon) assertNull(row.description) - assertEquals(emptyList(), row.badges) + assertEquals(KiloBundle.message("session.part.tool.running"), row.badges.single().text) assertNull(row.trailing) assertEquals(HistoryTime.title(HistoryTime.section(LocalHistoryItem(session))), row.section) } + fun `test plan session row shows activity badge without leading icon`() { + manager.kinds = mapOf("ses_1" to SessionActivityKind.PLAN) + rpc.listed += session("ses_1", nowSeconds()) + edt { controller.reload() } + flush() + + val row = row("ses_1") + + assertNull(row.icon) + assertEquals(KiloBundle.message("history.badge.plan"), row.badges.single().text) + } + fun `test session row shows the live agent title over the listed placeholder`() { rpc.listed += session("ses_1", nowSeconds()).copy(title = "New session - 2026-07-30T19:01:40.945Z") edt { controller.reload() } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt index f0f826d95f50..c8ea4f031e44 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt @@ -64,4 +64,18 @@ class UiStyleTest : BasePlatformTestCase() { assertSame(UiStyle.Badge.PullRequestMerged, style(GhState.MERGED)) assertSame(UiStyle.Badge.PullRequestClosed, style(GhState.CLOSED)) } + + fun `test pull request badges use soft accent backgrounds`() { + val styles = listOf( + UiStyle.Badge.PullRequestOpen, + UiStyle.Badge.PullRequestDraft, + UiStyle.Badge.PullRequestMerged, + UiStyle.Badge.PullRequestClosed, + ) + + styles.forEach { style -> + assertTrue(style.bg().alpha < Color.WHITE.alpha) + assertEquals(Color.WHITE.alpha, style.fg().alpha) + } + } } From 59d1ec8a22b8fc055c988db365ec89fd3aa66c43 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 09:36:44 -0400 Subject: [PATCH 09/30] feat(jetbrains): reorder worktrees with drag and drop --- .changeset/jetbrains-worktree-drag-reorder.md | 5 + .../backend/rpc/KiloWorktreeRpcApiImpl.kt | 17 ++ .../backend/rpc/KiloWorktreeRpcApiImplTest.kt | 33 ++++ .../client/agentManager/AgentManagerPanel.kt | 5 + .../worktree/KiloWorktreeService.kt | 7 + .../worktree/WorktreeController.kt | 19 ++ .../ai/kilocode/client/ui/list/ActiveList.kt | 3 +- .../client/ui/list/ActiveListModel.kt | 2 +- .../client/ui/list/ActiveListRenderer.kt | 76 ++++++++ .../client/ui/list/ActiveListReorder.kt | 84 +++++++++ .../kilocode/client/ui/list/ActiveListView.kt | 118 +++++++++++- .../agentManager/AgentManagerPanelTest.kt | 102 +++++++++++ .../client/testing/FakeWorktreeRpcApi.kt | 8 + .../client/ui/list/ActiveListReorderTest.kt | 173 ++++++++++++++++++ .../ai/kilocode/rpc/KiloWorktreeRpcApi.kt | 6 + 15 files changed, 654 insertions(+), 4 deletions(-) create mode 100644 .changeset/jetbrains-worktree-drag-reorder.md create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt create mode 100644 packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt diff --git a/.changeset/jetbrains-worktree-drag-reorder.md b/.changeset/jetbrains-worktree-drag-reorder.md new file mode 100644 index 000000000000..e18ec1ec2649 --- /dev/null +++ b/.changeset/jetbrains-worktree-drag-reorder.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": minor +--- + +Reorder Agent Manager worktrees by dragging them in the JetBrains plugin. diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt index 07a12ddc98c7..7e78ab891eec 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt @@ -328,6 +328,23 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi { } } + override suspend fun reorder(directory: String, paths: List): Boolean = + withContext(Dispatchers.IO) { + val base = Path.of(directory).normalize() + val res = runGit(base, "worktree", "list", "--porcelain") + if (!res.ok) return@withContext false + val items = managedWorktrees(parseWorktreeList(res.stdout)) + val store = worktreeNameStore(items) ?: return@withContext false + return@withContext try { + val state = readWorktreeState(store) + writeWorktreeState(store, state.copy(worktreeOrder = paths).reconcile(worktreePaths(items))) + true + } catch (e: Exception) { + LOG.warn("worktree reorder failed: dir=$directory message=${e.message}", e) + false + } + } + private data class GitResult(val exit: Int, val stdout: String, val stderr: String) { val ok get() = exit == 0 } diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt index f10524839047..4ebba6388ab3 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt @@ -241,6 +241,39 @@ class KiloWorktreeRpcApiImplTest { assertEquals(listOf(first.path, second.path), readWorktreeState(repo.resolve(".kilo").resolve("worktree-names.json")).worktreeOrder) } + @Test + fun `reorder persists a new order that a later list returns`() = runBlocking { + initRepo() + val first = assertNotNull(api.create(repo.toString(), CreateWorktreeRequestDto("zebra")).worktree) + val second = assertNotNull(api.create(repo.toString(), CreateWorktreeRequestDto("alpha")).worktree) + + assertTrue(api.reorder(repo.toString(), listOf(second.path, first.path))) + + val listed = api.list(repo.toString()).worktrees.filter { !it.main } + assertEquals(listOf(second.path, first.path), listed.map { it.path }) + assertEquals( + listOf(second.path, first.path), + readWorktreeState(repo.resolve(".kilo").resolve("worktree-names.json")).worktreeOrder, + ) + } + + @Test + fun `reorder drops unknown paths and appends omitted worktrees`() = runBlocking { + initRepo() + val first = assertNotNull(api.create(repo.toString(), CreateWorktreeRequestDto("zebra")).worktree) + val second = assertNotNull(api.create(repo.toString(), CreateWorktreeRequestDto("alpha")).worktree) + + assertTrue(api.reorder(repo.toString(), listOf("/does/not/exist", second.path))) + + val order = readWorktreeState(repo.resolve(".kilo").resolve("worktree-names.json")).worktreeOrder + assertEquals(listOf(second.path, first.path), order) + } + + @Test + fun `reorder returns false when the repo has no worktrees`() = runBlocking { + assertFalse(api.reorder(repo.toString(), listOf("/repo/.kilo/worktrees/x"))) + } + @Test fun `remove prunes names and order from worktree state`() = runBlocking { initRepo() diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 20b4007d0fe5..9face930132d 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -31,6 +31,7 @@ import ai.kilocode.client.ui.list.ActiveListDeleteOptions import ai.kilocode.client.ui.list.ActiveListItem import ai.kilocode.client.ui.list.ActiveListMenu import ai.kilocode.client.ui.list.ActiveListMetrics +import ai.kilocode.client.ui.list.ActiveListReorder import ai.kilocode.client.ui.list.ActiveListSelection import ai.kilocode.client.ui.list.ActiveListSurface import ai.kilocode.client.ui.list.activeListToolWindowBackground @@ -94,6 +95,10 @@ class AgentManagerPanel( menu = ActiveListMenu(WorktreeDataKeys.WORKTREE, group, element = { row -> (row as? WorktreeRow)?.dto?.takeIf { canRename(it) || canDelete(it) || canOpenPr(it) || canOpenDiff(it) } }), + reorder = ActiveListReorder( + movable = { row -> row is WorktreeRow && !row.current && !row.pending && !row.deleting }, + onMove = { move -> controller.reorder(move.keys) }, + ), ) private var selected: String? = null private var stats: Map = emptyMap() diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt index c5ccf4f2a227..6cf40e280edf 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt @@ -127,4 +127,11 @@ class KiloWorktreeService internal constructor( LOG.warn("worktree adopt failed for $path", e) RenameWorktreeResultDto(error = e.message ?: "worktree adopt failed") } + + suspend fun reorder(directory: String, paths: List): Boolean = try { + call { reorder(directory, paths) } + } catch (e: Exception) { + LOG.warn("worktree reorder failed for $directory", e) + false + } } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt index a3d58205b466..8e0d4c31ee7e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt @@ -240,6 +240,25 @@ class WorktreeController( } } + /** + * Applies a new display order given as worktree row [keys] (ids). Reorders the model optimistically + * then persists the resulting paths via [KiloWorktreeService.reorder]; on failure the list reloads + * from git ground truth. Pending rows keep their relative slots (stable sort) and are not persisted. + */ + fun reorder(keys: List) { + val rows = (0 until model.size).map { model.getElementAt(it) } + val rank = keys.withIndex().associate { it.value to it.index } + val sorted = rows.sortedBy { rank[it.id] ?: Int.MAX_VALUE } + if (sorted == rows) return + model.replaceAll(sorted) + val paths = sorted.filter { !isPending(it.id) }.map { it.path } + cs.launch { + val ok = service.reorder(directory, paths) + if (!ok) edt { reload() } + edt { telemetry("Worktree Reordered", mapOf("count" to paths.size.toString())) } + } + } + /** * Applies a name recorded elsewhere (e.g. adopted from a session title in an editor tab) to the * matching row, so the worktree list reflects it live. No-ops when the path is not in this list diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt index 46becf2dbc91..bdbbb2fecdcf 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt @@ -45,8 +45,9 @@ internal class ActiveList( onClick: ((ActiveListItem) -> Unit)? = null, onSelect: (() -> Unit)? = null, menu: ActiveListMenu<*>? = null, + reorder: ActiveListReorder? = null, ) : BorderLayoutPanel() { - private val view = ActiveListView(emptyText, cfg, surface, matcher, enter, openOnClick, onOpen, onActivate, onClick, menu, onCell) + private val view = ActiveListView(emptyText, cfg, surface, matcher, enter, openOnClick, onOpen, onActivate, onClick, menu, reorder, onCell) private val search: SearchTextField? = if (showSearch) SearchTextField(false) else null private val scroll = object : JBScrollPane(view) { override fun getBackground(): Color { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt index edf5d375e04c..ca40179423b5 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt @@ -224,7 +224,7 @@ internal fun activeListCellAt( return activeListCellAt(list, index, point, selected, false) } -private fun activeListLayout(component: Component) { +internal fun activeListLayout(component: Component) { if (component !is Container) return component.doLayout() for (child in component.components) activeListLayout(child) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt index 012afdf62c61..1bed3a9390d0 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt @@ -20,10 +20,17 @@ import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import ai.kilocode.rpc.dto.WorktreeStatsDto +import java.awt.AlphaComposite +import java.awt.BasicStroke import java.awt.BorderLayout import java.awt.Cursor import java.awt.Dimension +import java.awt.Graphics +import java.awt.Graphics2D +import java.awt.Point +import java.awt.RenderingHints import java.awt.Rectangle +import java.awt.image.BufferedImage import javax.swing.JList import javax.swing.JPanel import javax.swing.ListCellRenderer @@ -125,6 +132,7 @@ internal class ActiveListRenderer( ) private val wrap = PickerRow() private var bodyHeight: Int? = null + private var gap = false init { isOpaque = true @@ -199,6 +207,19 @@ internal class ActiveListRenderer( Dimension(0, height + JBUI.scale(2)) }) + if (value is ActiveListGap) { + gap = true + layers.isVisible = false + pill.isVisible = false + glyph.isVisible = false + wrap.update(list, false, false) + wrap.setPreferredSize(Dimension(0, bodyHeight ?: value.height)) + top.invalidate() + return this + } + gap = false + layers.isVisible = true + title.clear() title.append(value.title, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, titleFg)) value.note?.takeIf { it.isNotBlank() }?.let { @@ -245,6 +266,33 @@ internal class ActiveListRenderer( return this } + override fun paintChildren(g: Graphics) { + super.paintChildren(g) + if (!gap) return + val g2 = g.create() as Graphics2D + try { + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + val inset = UiStyle.Gap.xs() + val arc = UiStyle.Arc.component() + val x = wrap.x + inset + val y = wrap.y + inset + val width = (wrap.width - inset * 2 - 1).coerceAtLeast(0) + val height = (wrap.height - inset * 2 - 1).coerceAtLeast(0) + g2.color = JBUI.CurrentTheme.List.Selection.background(true) + g2.stroke = BasicStroke( + JBUI.scale(1).toFloat(), + BasicStroke.CAP_ROUND, + BasicStroke.JOIN_ROUND, + 0f, + floatArrayOf(JBUI.scale(3).toFloat(), JBUI.scale(3).toFloat()), + 0f, + ) + g2.drawRoundRect(x, y, width, height, arc, arc) + } finally { + g2.dispose() + } + } + fun setBodyHeight(height: Int?) { if (bodyHeight == height) return bodyHeight = height @@ -265,6 +313,34 @@ internal class ActiveListRenderer( return height } + /** + * Paints the row body — the section-header band excluded — into an image, together with the + * body's origin inside the cell so callers can map a grab point in cell coordinates onto the + * image. Rendered as the focused selection so the dragged copy reads as a lifted row. + */ + fun rowImage( + list: JList, + value: ActiveListItem, + index: Int, + width: Int, + ): Pair? { + getListCellRendererComponent(list, value, index, true, true) + val size = preferredSize + setBounds(0, 0, width, size.height) + activeListLayout(this) + if (wrap.width <= 0 || wrap.height <= 0) return null + val image = UIUtil.createImage(list, wrap.width, wrap.height, BufferedImage.TYPE_INT_ARGB) + val g2 = image.createGraphics() + try { + g2.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f) + g2.translate(-wrap.x, -wrap.y) + wrap.paint(g2) + } finally { + g2.dispose() + } + return image to Point(wrap.x, wrap.y) + } + private fun syncBadges(item: ActiveListItem) { val items = if (item.deleting) emptyList() else item.badges while (badges.componentCount > items.size) badges.remove(badges.componentCount - 1) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt new file mode 100644 index 000000000000..719331ffb893 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt @@ -0,0 +1,84 @@ +package ai.kilocode.client.ui.list + +import com.intellij.ide.dnd.DnDDragStartBean +import com.intellij.ide.dnd.DnDImage +import com.intellij.ide.dnd.DnDSupport +import com.intellij.ide.dnd.SmoothAutoScroller +import com.intellij.ui.components.JBList +import java.awt.GraphicsEnvironment +import java.awt.Point +import javax.swing.JList +import javax.swing.TransferHandler + +internal class ActiveListReorder( + val movable: (ActiveListItem) -> Boolean = { true }, + val onMove: (ActiveListMove) -> Unit, +) + +internal data class ActiveListMove( + val key: String, + val from: Int, + val to: Int, + val keys: List, +) + +internal data class ActiveListGap( + val source: ActiveListItem, + val height: Int, +) : ActiveListItem { + override val key: String get() = source.key + override val title: String get() = "" + override val section: String? get() = source.section + override val disabled: Boolean get() = true +} + +internal fun activeListGapRows(rows: List, key: String, index: Int, height: Int): List { + val from = rows.indexOfFirst { it.key == key } + if (from < 0) return rows + val source = rows[from] + val out = rows.toMutableList() + out.removeAt(from) + out.add(index.coerceIn(0, out.size), ActiveListGap(source, height)) + return out +} + +internal fun activeListSectionRun(rows: List, index: Int): IntRange { + if (index !in rows.indices) return 0 until 0 + val section = rows[index].section + val start = generateSequence(index) { it - 1 }.takeWhile { it >= 0 && rows[it].section == section }.last() + val end = generateSequence(index) { it + 1 }.takeWhile { it < rows.size && rows[it].section == section }.last() + return start..end +} + +internal fun installActiveListReorder(view: ActiveListView, list: JBList, reorder: ActiveListReorder) { + if (GraphicsEnvironment.isHeadless()) return + list.transferHandler = TransferHandler(null) + list.dragEnabled = true + SmoothAutoScroller.installDropTargetAsNecessary(list) + DnDSupport.createBuilder(list) + .setBeanProvider { info -> view.pickable(info.point)?.let { DnDDragStartBean(ActiveListPick(list, it)) } } + .setImageProvider { info -> + val pair = view.dragImage(info.point) ?: return@setImageProvider null + DnDImage(pair.first, pair.second) + } + .setTargetChecker { event -> + val pick = event.attachedObject as? ActiveListPick + if (pick?.list !== list) { + event.setDropPossible(false) + return@setTargetChecker true + } + event.setDropPossible(true) + view.over(pick.key, event.getPointOn(list)) + true + } + .setDropHandlerWithResult { event -> + val pick = event.attachedObject as? ActiveListPick + if (pick?.list !== list) return@setDropHandlerWithResult false + view.drop() + true + } + .setDropEndedCallback { view.cancel() } + .install() +} + +private data class ActiveListPick(val list: JList<*>, val key: String) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt index 59f678aecee4..a09df084bc04 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt @@ -21,6 +21,7 @@ import com.intellij.xml.util.XmlStringUtil import java.awt.Color import java.awt.Cursor import java.awt.Dimension +import java.awt.Image import java.awt.Point import java.awt.Rectangle import java.awt.event.FocusAdapter @@ -47,6 +48,7 @@ internal class ActiveListView( private val onActivate: ((ActiveListItem) -> Unit)? = null, private val onClick: ((ActiveListItem) -> Unit)? = null, private val menu: ActiveListMenu<*>? = null, + private val reorder: ActiveListReorder? = null, private val onCell: (String, String) -> Unit, ) : Stack(StackAxis.VERTICAL), Scrollable { private val model = CollectionListModel() @@ -98,6 +100,7 @@ internal class ActiveListView( private var popups = 0 private var hovered = -1 private var heightKey: ActiveListHeightKey? = null + private var drag: Drag? = null // Cursor for the row body; buttons override it on hover via [cursorAt]. private var baseCursor: Cursor = Cursor.getDefaultCursor() internal var onSelect: (() -> Unit)? = null @@ -173,7 +176,7 @@ internal class ActiveListView( } override fun mouseMoved(e: MouseEvent) { - if (hover) { + if (hover && drag == null) { val idx = list.locationToIndex(e.point) .takeIf { it >= 0 && list.getCellBounds(it, it)?.contains(e.point) == true } ?: -1 @@ -200,6 +203,7 @@ internal class ActiveListView( override fun focusLost(e: FocusEvent) = list.repaint() }) + reorder?.let { installActiveListReorder(this, list, it) } ScrollingUtil.installActions(list) next(list) } @@ -343,7 +347,10 @@ internal class ActiveListView( private fun sync(prefer: String? = list.selectedValue?.key, at: Int? = null, scroll: Boolean = true) { checkEdt() val q = filter.trim() - val rows = if (q.isBlank()) items else items.filter { matcher(q, it) } + val base = if (q.isBlank()) items else items.filter { matcher(q, it) } + val state = drag + if (state != null && base.none { it.key == state.key }) drag = null + val rows = drag?.let { activeListGapRows(base, it.key, it.index, it.height) } ?: base // Rebuilding the model fires a list-wide repaint, so skip it when the visible rows are // structurally unchanged (e.g. a stats/name refresh that produced identical rows) and only // reconcile selection below. Row types are data classes, so equality is by value. @@ -435,6 +442,7 @@ internal class ActiveListView( private fun open(focus: Boolean) { val item = list.selectedValue ?: return + if (item is ActiveListGap) return if (item.deleting) return val action = onOpen if (action != null) { @@ -446,6 +454,7 @@ internal class ActiveListView( private fun source() { val item = list.selectedValue ?: return + if (item is ActiveListGap) return if (item.deleting) return onOpen?.invoke(item, true) } @@ -457,6 +466,7 @@ internal class ActiveListView( * action is destructive (e.g. delete) does nothing on double-click. */ private fun activate(item: ActiveListItem) { + if (item is ActiveListGap) return if (item.deleting) return val action = onActivate if (action != null) { @@ -473,6 +483,7 @@ internal class ActiveListView( } private fun primary(item: ActiveListItem) { + if (item is ActiveListGap) return if (item.deleting) return val cells = activeListVisibleCells(item, true) val cell = cells.firstOrNull { it.enabled && it.primary } @@ -507,6 +518,95 @@ internal class ActiveListView( if (action != null) action() else onCell(item.key, id) } + @RequiresEdt + fun pickable(point: Point): String? { + checkEdt() + val cfg = reorder ?: return null + if (!list.isEnabled || filter.isNotBlank() || drag != null) return null + val idx = rowAt(point) ?: return null + val item = model.getElementAt(idx) + if (item is ActiveListGap || item.disabled || item.deleting) return null + if (!cfg.movable(item)) return null + val selected = list.isSelectedIndex(idx) + if (activeListCellAt(list, idx, point, selected, menu?.takeIf { it.available(item) } != null) != null) return null + return item.key + } + + /** + * The dragged row painted as an image, plus the AWT image offset that keeps the grabbed pixel + * under the cursor. AWT places the image origin at `cursor + offset`, so the offset is the + * negated grab point inside the image — otherwise the copy floats off to the lower right. + */ + @RequiresEdt + fun dragImage(point: Point): Pair? { + checkEdt() + val idx = rowAt(point) ?: return null + val item = model.getElementAt(idx) + if (item is ActiveListGap) return null + val bounds = list.getCellBounds(idx, idx) ?: return null + val (image, origin) = renderer.rowImage(list, item, idx, bounds.width) ?: return null + // Clamp so grabbing the section-header band still anchors inside the body image. + val x = (point.x - bounds.x - origin.x).coerceIn(0, image.width) + val y = (point.y - bounds.y - origin.y).coerceIn(0, image.height) + return image to Point(-x, -y) + } + + @RequiresEdt + fun over(key: String, point: Point) { + checkEdt() + if (filter.isNotBlank()) return + val current = drag + val base = items + val from = activeListIndex(base, key) + if (from < 0) { + cancel() + return + } + val bounds = list.getCellBounds(from, from) + val state = current ?: Drag(key, from, from, bounds?.height ?: list.fixedCellHeight.takeIf { it > 0 } ?: renderer.bodyPreferredHeight(list, base[from], from, true, true)) + if (current == null) { + press = null + setHovered(-1) + drag = state + } + val run = activeListSectionRun(base, from) + if (run.isEmpty()) return + val idx = rowAt(point) ?: state.index + val next = idx.coerceIn(run.first, run.last) + if (state.index == next && current != null) return + drag = state.copy(index = next) + sync(key, next, scroll = false) + } + + @RequiresEdt + fun drop() { + checkEdt() + val state = drag ?: return + drag = null + val source = activeListIndex(items, state.key) + if (source < 0) { + sync() + return + } + val rows = items.toMutableList() + val item = rows.removeAt(source) + val target = state.index.coerceIn(0, rows.size) + rows.add(target, item) + items = rows + heightKey = null + sync(state.key, target, scroll = false) + if (source == target) return + reorder?.onMove?.invoke(ActiveListMove(state.key, source, target, rows.map { it.key })) + } + + @RequiresEdt + fun cancel() { + checkEdt() + if (drag == null) return + drag = null + sync() + } + @RequiresEdt fun setBaseCursor(cursor: Cursor) { checkEdt() @@ -527,6 +627,7 @@ internal class ActiveListView( val bounds = idx.takeIf { it >= 0 }?.let { list.getCellBounds(it, it) } ?: return baseCursor if (!bounds.contains(point)) return baseCursor val item = model.getElementAt(idx) + if (item is ActiveListGap) return baseCursor if (menu == null && item.cells.isEmpty() && item.metrics == null) return baseCursor val hit = activeListHits(list, idx, list.isSelectedIndex(idx)) .firstOrNull { it.enabled && it.bounds.contains(point) } @@ -539,6 +640,7 @@ internal class ActiveListView( val bounds = idx.takeIf { it >= 0 }?.let { list.getCellBounds(it, it) } ?: return null if (!bounds.contains(e.point)) return null val item = model.getElementAt(idx) + if (item is ActiveListGap) return null val selected = list.isSelectedIndex(idx) val id = if (enabled) { activeListCellAt(list, idx, e.point, selected, menu?.takeIf { it.available(item) } != null) @@ -557,6 +659,7 @@ internal class ActiveListView( val bounds = idx.takeIf { it >= 0 }?.let { list.getCellBounds(it, it) } ?: return false if (!bounds.contains(point)) return false val item = model.getElementAt(idx) + if (item is ActiveListGap) return false if (item.disabled || item.deleting || !cfg.available(item)) return false val rect = activeListCellBounds(list, idx, list.isSelectedIndex(idx))[ACTIVE_LIST_MENU_CELL] ?: return false if (!rect.contains(point)) return false @@ -603,6 +706,15 @@ internal class ActiveListView( return e.isShiftDown || e.isMetaDown || e.isControlDown } + private fun rowAt(point: Point): Int? { + val idx = list.locationToIndex(point) + if (idx < 0) return null + val bounds = list.getCellBounds(idx, idx) ?: return null + if (bounds.contains(point)) return idx + if (point.y < bounds.y) return 0 + return (model.size - 1).takeIf { it >= 0 } + } + override fun getBackground(): Color { if (surface == ActiveListSurface.ToolWindow) return activeListToolWindowBackground() return super.getBackground() ?: UIUtil.getPanelBackground() @@ -637,6 +749,8 @@ internal class ActiveListView( private data class Press(val key: String, val id: String) + private data class Drag(val key: String, val from: Int, val index: Int, val height: Int) + private data class ActiveListHeightKey( val cfg: ActiveListConfig, val width: Int, diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index 561d04b0d411..d2d2f8c7a963 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -22,6 +22,7 @@ import ai.kilocode.client.testing.fire import ai.kilocode.client.ui.list.ActiveListBadge import ai.kilocode.client.ui.list.ActiveListItem import ai.kilocode.client.ui.list.ActiveListMetrics +import ai.kilocode.client.ui.list.ActiveListView import ai.kilocode.client.ui.list.ACTIVE_LIST_PR_CELL import ai.kilocode.client.ui.list.activeListCellBounds import ai.kilocode.client.ui.list.activeListToolWindowBackground @@ -610,6 +611,107 @@ class AgentManagerPanelTest : BasePlatformTestCase() { flush() } + fun `test dragging a worktree above another reorders the model and persists the path order`() { + val a = worktree("aardvark") + val b = worktree("beluga") + rpc.listed += main() + rpc.listed += a + rpc.listed += b + val controller = WorktreeController(service, project.basePath!!, coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + + val view = edt { UIUtil.findComponentOfType(panel, ActiveListView::class.java)!! } + layout(view) + // Display order: current (main) row is index 0, then a (1), b (2). + edt { + assertEquals(b.id, view.pickable(rowCenter(view, 2))) + view.over(b.id, rowCenter(view, 1)) + view.drop() + } + flush() + + assertEquals(listOf(b.path, a.path), edt { worktreeIds(controller) }) + assertEquals(listOf(listOf(b.path, a.path)), rpc.reorders.toList()) + } + + fun `test the current and pending rows are not draggable`() { + rpc.listed += main() + rpc.listed += worktree("aardvark") + val controller = WorktreeController(service, project.basePath!!, coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + + val gate = CompletableDeferred() + rpc.beforeCreate = { gate.await() } + edt { controller.create("feature/pending", null) } + val view = edt { UIUtil.findComponentOfType(panel, ActiveListView::class.java)!! } + layout(view) + + edt { + val size = view.list.model.size + // Row 0 is the current (main) row; the last row is the pending create. + assertNull(view.pickable(rowCenter(view, 0))) + assertNull(view.pickable(rowCenter(view, size - 1))) + } + gate.complete(Unit) + flush() + } + + fun `test a failed reorder rpc reloads from git ground truth`() { + val a = worktree("aardvark") + val b = worktree("beluga") + rpc.listed += main() + rpc.listed += a + rpc.listed += b + rpc.reorderResult = false + val controller = WorktreeController(service, project.basePath!!, coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + + val view = edt { UIUtil.findComponentOfType(panel, ActiveListView::class.java)!! } + layout(view) + edt { + view.over(b.id, rowCenter(view, 1)) + view.drop() + } + flush() + + // The optimistic swap is discarded; reload restores the backend (listed) order. + assertEquals(listOf(a.path, b.path), edt { worktreeIds(controller) }) + assertEquals(listOf(listOf(b.path, a.path)), rpc.reorders.toList()) + } + + private fun main(): WorktreeDto { + val base = project.basePath!! + return WorktreeDto(base, "repo", "main", base, main = true) + } + + private fun worktree(name: String): WorktreeDto { + val path = "${project.basePath!!}/.kilo/worktrees/$name" + return WorktreeDto(path, name, name, path) + } + + private fun worktreeIds(controller: WorktreeController): List { + return (0 until controller.model.size).map { controller.model.getElementAt(it).path } + } + + private fun layout(view: ActiveListView) { + edt { + view.list.setSize(360, 600) + view.list.doLayout() + UIUtil.dispatchAllInvocationEvents() + } + } + + private fun rowCenter(view: ActiveListView, index: Int): Point { + val bounds = view.list.getCellBounds(index, index)!! + return Point(bounds.x + 8, bounds.y + bounds.height / 2) + } + private fun edt(block: () -> T): T = edtWait(block) private fun flush() = coroutines.drain(::pump) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt index 6560dc5c5b58..697ff0fbd33c 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt @@ -29,6 +29,8 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { val removeForces = CopyOnWriteArrayList() val renames = CopyOnWriteArrayList>() val adopts = CopyOnWriteArrayList>() + val reorders = CopyOnWriteArrayList>() + var reorderResult = true val opens = CopyOnWriteArrayList() val ghCalls = CopyOnWriteArrayList() var beforeCreate: suspend () -> Unit = {} @@ -123,4 +125,10 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { adopts.add(Triple(directory, path, name)) return adoptResult(path, name) } + + override suspend fun reorder(directory: String, paths: List): Boolean { + assertNotEdt("reorder") + reorders.add(paths) + return reorderResult + } } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt new file mode 100644 index 000000000000..57c7d6ea8a80 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt @@ -0,0 +1,173 @@ +package ai.kilocode.client.ui.list + +import com.intellij.testFramework.fixtures.BasePlatformTestCase +import com.intellij.util.ui.UIUtil +import java.awt.Point +import java.awt.Rectangle + +class ActiveListReorderTest : BasePlatformTestCase() { + + fun `test gap rows remove the dragged row and insert a placeholder at the index`() { + val rows = rows("a", "b", "c") + val out = activeListGapRows(rows, "c", 0, 20) + assertEquals(listOf("c", "a", "b"), out.map { it.key }) + assertTrue(out[0] is ActiveListGap) + assertEquals(3, out.size) + } + + fun `test gap rows keep the dragged key so selection stays anchored`() { + val rows = rows("a", "b", "c") + val out = activeListGapRows(rows, "b", 2, 20) + assertEquals(listOf("a", "c", "b"), out.map { it.key }) + } + + fun `test section run spans only rows sharing the section`() { + val rows = listOf(row("cur", null), row("a", "wt"), row("b", "wt"), row("c", "wt")) + assertEquals(0..0, activeListSectionRun(rows, 0)) + assertEquals(1..3, activeListSectionRun(rows, 1)) + assertEquals(1..3, activeListSectionRun(rows, 3)) + } + + fun `test pick up opens a gap and drop reorders firing the move`() { + val moves = mutableListOf() + val view = view(moves) + view.update(sectioned()) + layout(view) + + val point = center(view, 3) + assertEquals("c", view.pickable(point)) + view.over("c", center(view, 1)) + + // The real row is gone from the model; a gap holds its old key at the new index. + val display = display(view) + assertEquals(listOf("cur", "c", "a", "b"), display.map { it.key }) + assertTrue(display[1] is ActiveListGap) + + view.drop() + assertEquals(listOf("cur", "c", "a", "b"), display(view).map { it.key }) + val move = moves.single() + assertEquals("c", move.key) + assertEquals(3, move.from) + assertEquals(1, move.to) + assertEquals(listOf("cur", "c", "a", "b"), move.keys) + } + + fun `test drag cannot leave its section and never displaces the current row`() { + val moves = mutableListOf() + val view = view(moves) + view.update(sectioned()) + layout(view) + + view.over("c", center(view, 0)) + // Clamped to the first worktree slot, never above the current row. + assertEquals(listOf("cur", "c", "a", "b"), display(view).map { it.key }) + } + + fun `test cancel restores the original order and fires nothing`() { + val moves = mutableListOf() + val view = view(moves) + view.update(sectioned()) + layout(view) + + view.over("c", center(view, 1)) + view.cancel() + + assertEquals(listOf("cur", "a", "b", "c"), display(view).map { it.key }) + assertTrue(moves.isEmpty()) + } + + fun `test an external update that drops the dragged key cancels the drag`() { + val moves = mutableListOf() + val view = view(moves) + view.update(sectioned()) + layout(view) + + view.over("c", center(view, 1)) + // A refresh that no longer contains the dragged worktree (e.g. it was deleted mid-drag). + view.update(listOf(row("cur", null), row("a", "wt"), row("b", "wt"))) + + assertEquals(listOf("cur", "a", "b"), display(view).map { it.key }) + assertTrue(moves.isEmpty()) + } + + fun `test pickable rejects immovable rows and an active filter`() { + val view = view(mutableListOf()) + view.update(sectioned()) + layout(view) + + assertNull(view.pickable(center(view, 0))) + + view.filter("a") + layout(view) + assertNull(view.pickable(center(view, view.list.model.size - 1))) + } + + fun `test drag image anchors the grabbed pixel under the cursor`() { + val view = view(mutableListOf()) + view.update(sectioned()) + layout(view) + + val point = center(view, 3) + val image = view.dragImage(point) ?: error("expected a drag image") + assertTrue(image.first.getWidth(null) > 0) + assertTrue(image.first.getHeight(null) > 0) + // AWT draws the image at cursor + offset, so the offset is the negated grab point and the + // dragged copy sits exactly under the pointer instead of down and to the right of it. + val bounds = view.list.getCellBounds(3, 3)!! + assertEquals(-(point.x - bounds.x), image.second.x) + assertTrue(image.second.x <= 0) + assertTrue(image.second.y <= 0) + assertTrue(-image.second.y <= image.first.getHeight(null)) + } + + fun `test grabbing a section header row still anchors inside the body image`() { + val view = view(mutableListOf()) + view.update(sectioned()) + layout(view) + + // Row 1 carries the "wt" section band above its body; grab inside that band. + val bounds = view.list.getCellBounds(1, 1)!! + val image = view.dragImage(Point(bounds.x + 8, bounds.y + 1)) ?: error("expected a drag image") + assertEquals(0, image.second.y) + } + + private fun view(moves: MutableList): ActiveListView { + return ActiveListView( + empty = "", + reorder = ActiveListReorder( + movable = { it.section != null }, + onMove = { moves += it }, + ), + onCell = { _, _ -> }, + ) + } + + private fun layout(view: ActiveListView) { + view.setBounds(0, 0, 300, 600) + view.doLayout() + view.list.setBounds(0, 0, 300, 600) + view.list.doLayout() + UIUtil.dispatchAllInvocationEvents() + } + + private fun display(view: ActiveListView): List { + return (0 until view.list.model.size).map { view.list.model.getElementAt(it) } + } + + private fun center(view: ActiveListView, index: Int): Point { + val bounds: Rectangle = view.list.getCellBounds(index, index) ?: error("no bounds for $index") + return Point(bounds.x + 8, bounds.y + bounds.height / 2) + } + + private fun sectioned(): List { + return listOf(row("cur", null), row("a", "wt"), row("b", "wt"), row("c", "wt")) + } + + private fun rows(vararg keys: String): List = keys.map { row(it, "wt") } + + private fun row(key: String, section: String?): ActiveListItem = object : ActiveListItem { + override val key = key + override val title = key + override val section = section + } +} diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt index 63b7b09ef794..5c0a4dbba8fe 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt @@ -61,4 +61,10 @@ interface KiloWorktreeRpcApi : RemoteApi { * null error when it was skipped because a custom name already exists. */ suspend fun adopt(directory: String, path: String, name: String): RenameWorktreeResultDto + + /** + * Records [paths] as the worktree display order for [directory], reconciled against + * `git worktree list` (unknown paths dropped, missing ones appended). Returns true when written. + */ + suspend fun reorder(directory: String, paths: List): Boolean } From 07d2189d319c47e78e70ed428b96abe4fd33de18 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 12:40:52 -0400 Subject: [PATCH 10/30] fix(jetbrains): keep list selection stable across refreshes ActiveList rebuilt its model with CollectionListModel.replaceAll, which fires an intervalRemoved with an empty model. The old sync() then fell back to selecting row 0, and that spurious selection fired onSelect, clobbering the caller's remembered row. Dropping a dragged worktree and switching away from the Agents tab both hit this path, so the selection jumped to the first row. Give ActiveList one capture -> refresh -> restore path: rows expose a stable identity, the view remembers the selected identities as a sticky anchor written only by user intent, and restores them after every rebuild with an explicit absent-row policy. This removes the four hand-rolled restore blocks in AgentManagerPanel, HistoryPanel, and SettingsInlineListPanel, along with the AgentManagerPanel.selected mirror and the settings syncing guard. --- .changeset/jetbrains-list-selection-sync.md | 5 + .../client/agentManager/AgentManagerPanel.kt | 19 +-- .../client/session/history/HistoryPanel.kt | 14 +- .../settings/base/SettingsInlineListPanel.kt | 10 +- .../ai/kilocode/client/ui/list/ActiveList.kt | 2 +- .../client/ui/list/ActiveListModel.kt | 5 + .../kilocode/client/ui/list/ActiveListView.kt | 149 ++++++++++++++---- .../agentManager/AgentManagerPanelTest.kt | 61 +++++++ .../client/ui/list/ActiveListReorderTest.kt | 14 ++ .../client/ui/list/ActiveListSelectionTest.kt | 135 ++++++++++++++++ 10 files changed, 345 insertions(+), 69 deletions(-) create mode 100644 .changeset/jetbrains-list-selection-sync.md create mode 100644 packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt diff --git a/.changeset/jetbrains-list-selection-sync.md b/.changeset/jetbrains-list-selection-sync.md new file mode 100644 index 000000000000..bf93f305848a --- /dev/null +++ b/.changeset/jetbrains-list-selection-sync.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Keep Agent Manager worktree selection stable when reordering worktrees and switching tabs. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 9face930132d..5b7f2578793b 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -91,7 +91,6 @@ class AgentManagerPanel( val item = (row as? WorktreeRow)?.dto ?: return@ActiveList open(item, focus) }, - onSelect = { selectedRow()?.dto?.id?.let { selected = it } }, menu = ActiveListMenu(WorktreeDataKeys.WORKTREE, group, element = { row -> (row as? WorktreeRow)?.dto?.takeIf { canRename(it) || canDelete(it) || canOpenPr(it) || canOpenDiff(it) } }), @@ -100,7 +99,6 @@ class AgentManagerPanel( onMove = { move -> controller.reorder(move.keys) }, ), ) - private var selected: String? = null private var stats: Map = emptyMap() private var prs: Map = emptyMap() @@ -150,7 +148,7 @@ class AgentManagerPanel( } fun refresh() { - selected = selected ?: currentEditorWorktree() + if (list.selectedKeys().isEmpty()) currentEditorWorktree()?.let { list.select(it, scroll = false) } controller.reload() project?.service()?.refreshStats() project?.service()?.refreshPr() @@ -276,9 +274,7 @@ class AgentManagerPanel( * last row when the removed row was last) and opens it before closing the deleted tab so the * neighbour becomes the active editor. Deleting a background row leaves the selection untouched. * - * The active editor is read before close(item) as the ground-truth "shown" signal; the - * `selected` field is unreliable here because the model rebuild in sync() transiently reselects - * row 0 through the list's onSelect hook. + * The active editor is read before close(item) as the ground-truth "shown" signal. */ private fun onRemoved(item: WorktreeDto, index: Int) { if (currentEditorWorktree() == item.id) advance(neighbor(index)) @@ -292,7 +288,6 @@ class AgentManagerPanel( * the selection somewhere unpredictable. */ private fun advance(next: WorktreeDto?) { - selected = next?.id if (next == null) { list.clearSelection() return @@ -353,7 +348,6 @@ class AgentManagerPanel( } private fun sync() { - val key = selected val current = controller.current?.let { item -> WorktreeRow( item, @@ -382,26 +376,18 @@ class AgentManagerPanel( }, ActiveListSelection.PreserveNoScroll, ) - if (key != null) { - if (!list.select(key, scroll = false)) list.clearSelection() - return - } - list.clearSelection() - selected = null } @RequiresEdt private fun track(file: VirtualFile?) { val key = project?.service()?.match(file) if (key != null) { - selected = key list.select(key, scroll = false) return } // A null active editor is a transient state (e.g. a tab closing during a delete); keep the // current selection. Only a real, non-worktree editor clears the worktree row selection. if (file == null) return - selected = null list.clearSelection() } @@ -490,6 +476,7 @@ class AgentManagerPanel( val current: Boolean = false, ) : ActiveListItem { override val key: String get() = dto.id + override val identity: Any get() = if (current) "local:${dto.path}" else "worktree:${dto.path}" override val title: String get() = if (current) dto.branch else WorktreeTitle.text(dto.name, dto.path, pr) override val description: String get() = WorktreeTitle.fallback(dto.path) override val tooltip: String? get() = null diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryPanel.kt index 65f485c1f7ec..06f793e782ff 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryPanel.kt @@ -286,19 +286,7 @@ class HistoryPanel( * list is now empty. */ private fun restore(list: ActiveList, rows: List) { - val keys = list.selectedKeys() - val anchor = list.selectedIndex() - list.update(rows, ActiveListSelection.PreserveNoScroll) - val indices = keys.mapNotNull { key -> rows.indexOfFirst { it.key == key }.takeIf { it >= 0 } }.toIntArray() - if (indices.isNotEmpty()) { - list.setSelectionIndices(indices) - return - } - if (keys.isNotEmpty() && rows.isNotEmpty()) { - list.selectIndex(anchor.coerceIn(0, rows.size - 1)) - return - } - list.clearSelection() + list.update(rows, ActiveListSelection.Slide) } @RequiresEdt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsInlineListPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsInlineListPanel.kt index 329256fa8cfe..fc07d2c4a765 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsInlineListPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsInlineListPanel.kt @@ -41,7 +41,6 @@ internal abstract class SettingsInlineListPanel( private val search = SearchTextField(false) protected val view = ActiveListView(emptyText, cfg) { key, cellId -> onCell(key, cellId) } private var toolbar: ActionToolbar? = null - private var syncing = false @RequiresEdt protected fun start() { @@ -51,7 +50,7 @@ internal abstract class SettingsInlineListPanel( view.setListMinimumSize(JBUI.size(0, minListHeight())) view.onSelect = { toolbar?.updateActionsImmediately() - if (!syncing) onSelectionChanged(selectedKeys()) + onSelectionChanged(selectedKeys()) } next(toolbarRow()) gap(UiStyle.Gap.sm()) @@ -81,12 +80,7 @@ internal abstract class SettingsInlineListPanel( fun setItems(items: List, enabled: Boolean) { checkEdt() setEnabled(enabled) - syncing = true - try { - view.update(items, ActiveListSelection.PreserveNoScroll) - } finally { - syncing = false - } + view.update(items, ActiveListSelection.PreserveNoScroll) toolbar?.updateActionsImmediately() } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt index bdbbb2fecdcf..e266dbde6098 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt @@ -129,7 +129,7 @@ internal class ActiveList( @RequiresEdt fun setSelectionIndices(indices: IntArray) { - view.list.selectedIndices = indices + view.setSelectionIndices(indices) } @RequiresEdt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt index ca40179423b5..51cecbdea447 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt @@ -90,6 +90,11 @@ internal interface ActiveListHitCell { */ internal interface ActiveListItem { val key: String + /** + * Stable identity used to restore selection across refreshes. Defaults to [key]; override when + * the key is not stable for the row's lifetime. + */ + val identity: Any get() = key val title: String val note: String? get() = null val description: String? get() = null diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt index a09df084bc04..84d7002e2d8c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt @@ -101,6 +101,9 @@ internal class ActiveListView( private var hovered = -1 private var heightKey: ActiveListHeightKey? = null private var drag: Drag? = null + private var anchor: Set = emptySet() + private var mark = -1 + private var restoring = false // Cursor for the row body; buttons override it on hover via [cursorAt]. private var baseCursor: Cursor = Cursor.getDefaultCursor() internal var onSelect: (() -> Unit)? = null @@ -131,6 +134,7 @@ internal class ActiveListView( list.requestFocusInWindow() press = null if (selection(e)) return + rowAt(e.point)?.takeIf { !list.isSelectedIndex(it) }?.let { choose(it, scroll = false) } val hit = hit(e) ?: return press = Press(hit.item.key, hit.id ?: return) } @@ -196,7 +200,11 @@ internal class ActiveListView( // Selection gates the hover-revealed action bar, so repaint the hovered row as soon as // its selection flips instead of waiting for the next mouse move. if (hover) repaintRow(hovered) - if (!e.valueIsAdjusting) onSelect?.invoke() + if (!restoring && !e.valueIsAdjusting) { + anchor = identities() + mark = list.selectedIndex + onSelect?.invoke() + } } list.addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent) = list.repaint() @@ -217,6 +225,8 @@ internal class ActiveListView( @RequiresEdt fun clearSelection() { checkEdt() + anchor = emptySet() + mark = -1 list.clearSelection() } @@ -241,7 +251,9 @@ internal class ActiveListView( @RequiresEdt fun select(key: String, scroll: Boolean = true): Boolean { checkEdt() + anchor = setOf(key) val idx = activeListIndex(model.items, key) + mark = idx if (idx < 0) return false choose(idx, scroll) return true @@ -250,9 +262,21 @@ internal class ActiveListView( @RequiresEdt fun selectIndex(index: Int) { checkEdt() + val item = model.items.getOrNull(index) + anchor = item?.let { setOf(it.identity) }.orEmpty() + mark = if (item == null) -1 else index choose(index) } + @RequiresEdt + fun setSelectionIndices(indices: IntArray) { + checkEdt() + val rows = indices.toList().mapNotNull { model.items.getOrNull(it) } + anchor = rows.map { it.identity }.toSet() + mark = indices.firstOrNull { it in model.items.indices } ?: -1 + list.selectedIndices = indices + } + @RequiresEdt fun setSelectionMode(mode: Int) { checkEdt() @@ -297,20 +321,18 @@ internal class ActiveListView( checkEdt() if (this.items != items) heightKey = null this.items = items - val key = when (selection) { - is ActiveListSelection.Key -> selection.key - is ActiveListSelection.Index -> null - ActiveListSelection.PreserveNoScroll, - ActiveListSelection.Preserve -> list.selectedValue?.key - } - val idx = when (selection) { - is ActiveListSelection.Index -> selection.index - is ActiveListSelection.Key, + val scroll = selection != ActiveListSelection.PreserveNoScroll + when (selection) { + is ActiveListSelection.Key -> { + anchor = setOf(selection.key) + mark = -1 + sync(Absent.KEEP, scroll) + } + is ActiveListSelection.Index -> sync(Absent.KEEP, scroll, selection.index, reanchor = true) + ActiveListSelection.Slide -> sync(Absent.SLIDE, scroll) ActiveListSelection.PreserveNoScroll, - ActiveListSelection.Preserve, - -> null + ActiveListSelection.Preserve -> sync(Absent.KEEP, scroll) } - sync(key, idx, selection != ActiveListSelection.PreserveNoScroll) } @RequiresEdt @@ -340,32 +362,79 @@ internal class ActiveListView( checkEdt() if (filter == query) return filter = query - sync() + sync(Absent.FIRST) } @RequiresEdt - private fun sync(prefer: String? = list.selectedValue?.key, at: Int? = null, scroll: Boolean = true) { + private fun sync(absent: Absent = Absent.KEEP, scroll: Boolean = true, at: Int? = null, reanchor: Boolean = false) { checkEdt() val q = filter.trim() val base = if (q.isBlank()) items else items.filter { matcher(q, it) } val state = drag if (state != null && base.none { it.key == state.key }) drag = null val rows = drag?.let { activeListGapRows(base, it.key, it.index, it.height) } ?: base - // Rebuilding the model fires a list-wide repaint, so skip it when the visible rows are - // structurally unchanged (e.g. a stats/name refresh that produced identical rows) and only - // reconcile selection below. Row types are data classes, so equality is by value. - if (model.items != rows) { - setHovered(-1) - model.replaceAll(rows) + restoring = true + try { + // Rebuilding the model fires a list-wide repaint, so skip it when the visible rows are + // structurally unchanged (e.g. a stats/name refresh that produced identical rows) and only + // reconcile selection below. Row types are data classes, so equality is by value. + if (model.items != rows) { + setHovered(-1) + model.replaceAll(rows) + } + syncCellHeight(rows) + restore(rows, absent, scroll, at, reanchor) + } finally { + restoring = false } - syncCellHeight(rows) + } + + @RequiresEdt + private fun restore(rows: List, absent: Absent, scroll: Boolean, at: Int?, reanchor: Boolean) { + checkEdt() val idx = at?.let { activeListIndex(rows, it) }?.takeIf { it >= 0 } - ?: activeListIndex(rows, prefer).takeIf { it >= 0 } - ?: rows.indices.firstOrNull() - ?: -1 - if (idx >= 0) choose(idx, scroll) else list.clearSelection() + if (idx != null) { + choose(idx, scroll) + mark = idx + if (reanchor) anchor = setOf(rows[idx].identity) + return + } + val indices = anchor.mapNotNull { id -> activeListIdentityIndex(rows, id).takeIf { it >= 0 } } + if (indices.isNotEmpty()) { + list.selectedIndices = indices.toIntArray() + mark = indices.first() + if (scroll) ScrollingUtil.ensureIndexIsVisible(list, mark, 0) + return + } + when (absent) { + Absent.KEEP -> { + list.clearSelection() + } + Absent.SLIDE -> { + if (anchor.isEmpty() || rows.isEmpty()) { + list.clearSelection() + mark = -1 + return + } + val next = mark.coerceIn(0, rows.lastIndex) + choose(next, scroll) + anchor = setOf(rows[next].identity) + mark = next + } + Absent.FIRST -> { + if (rows.isEmpty()) { + list.clearSelection() + return + } + choose(0, scroll) + mark = 0 + if (anchor.isEmpty()) anchor = setOf(rows[0].identity) + } + } } + private fun identities(): Set = list.selectedValuesList.map { it.identity }.toSet() + @RequiresEdt private fun setHovered(idx: Int) { checkEdt() @@ -436,12 +505,12 @@ internal class ActiveListView( @RequiresEdt fun primary() { checkEdt() - val item = list.selectedValue ?: return + val item = active() ?: return primary(item) } private fun open(focus: Boolean) { - val item = list.selectedValue ?: return + val item = active() ?: return if (item is ActiveListGap) return if (item.deleting) return val action = onOpen @@ -459,6 +528,13 @@ internal class ActiveListView( onOpen?.invoke(item, true) } + private fun active(): ActiveListItem? { + list.selectedValue?.let { return it } + if (model.size == 0) return null + choose(0, scroll = false) + return list.selectedValue + } + /** * Default action for a double-click. Resolves to the row's explicit activation only: an * [onActivate] handler, then the row's [ActiveListItem.doubleClick] cell, then a [primary] cell. @@ -575,7 +651,7 @@ internal class ActiveListView( val next = idx.coerceIn(run.first, run.last) if (state.index == next && current != null) return drag = state.copy(index = next) - sync(key, next, scroll = false) + sync(Absent.KEEP, scroll = false, at = next) } @RequiresEdt @@ -594,7 +670,9 @@ internal class ActiveListView( rows.add(target, item) items = rows heightKey = null - sync(state.key, target, scroll = false) + anchor = setOf(state.key) + mark = target + sync(Absent.KEEP, scroll = false, at = target) if (source == target) return reorder?.onMove?.invoke(ActiveListMove(state.key, source, target, rows.map { it.key })) } @@ -757,6 +835,8 @@ internal class ActiveListView( val rows: List, ) + private enum class Absent { KEEP, SLIDE, FIRST } + } private data class ActiveListHeightRow( @@ -790,18 +870,25 @@ private fun activeListHeightRow(item: ActiveListItem): ActiveListHeightRow { } private fun activeListIndex(items: List, key: String?): Int { - if (key == null) return if (items.isEmpty()) -1 else 0 + if (key == null) return -1 return items.indexOfFirst { it.key == key } } +private fun activeListIdentityIndex(items: List, id: Any): Int { + return items.indexOfFirst { it.identity == id || it.key == id } +} + private fun activeListIndex(items: List, index: Int): Int { if (items.isEmpty()) return -1 return index.coerceIn(0, items.lastIndex) } internal sealed interface ActiveListSelection { + /** Restore the remembered rows and scroll to them; select nothing while they are absent. */ data object Preserve : ActiveListSelection data object PreserveNoScroll : ActiveListSelection + /** Restore the remembered rows; when they are all gone, select the row that took their slot. */ + data object Slide : ActiveListSelection data class Key(val key: String) : ActiveListSelection data class Index(val index: Int) : ActiveListSelection } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index d2d2f8c7a963..b9c2c4182d28 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -234,6 +234,24 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(second.id, edt { (list.selectedValue as ActiveListItem).key }) } + fun `test panel refresh keeps selected worktree across tab switch reload`() { + val first = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") + val second = WorktreeDto("/repo/.kilo/worktrees/feature-y", "feature-y", "feature/y", "/repo/.kilo/worktrees/feature-y") + rpc.listed += first + rpc.listed += second + val controller = WorktreeController(service, "/test", coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + val list = edt { UIUtil.findComponentOfType(panel, JBList::class.java)!! } + edt { list.selectedIndex = 1 } + + edt { panel.refresh() } + flush() + + assertEquals(second.id, edt { (list.selectedValue as ActiveListItem).key }) + } + fun `test refresh keeps existing selection`() { val first = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") val second = WorktreeDto("/repo/.kilo/worktrees/feature-y", "feature-y", "feature/y", "/repo/.kilo/worktrees/feature-y") @@ -636,6 +654,49 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(listOf(listOf(b.path, a.path)), rpc.reorders.toList()) } + fun `test dragging a worktree keeps dropped row selected after reorder reload`() { + val a = worktree("aardvark") + val b = worktree("beluga") + rpc.listed += main() + rpc.listed += a + rpc.listed += b + val controller = WorktreeController(service, project.basePath!!, coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + + val view = edt { UIUtil.findComponentOfType(panel, ActiveListView::class.java)!! } + layout(view) + edt { + assertTrue(view.select(b.id)) + view.over(b.id, rowCenter(view, 1)) + view.drop() + } + flush() + + assertEquals(b.id, edt { view.selected()?.key }) + } + + fun `test renaming selected worktree keeps it selected`() { + val item = worktree("aardvark") + rpc.listed += main() + rpc.listed += item + val controller = WorktreeController(service, project.basePath!!, coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + + val view = edt { UIUtil.findComponentOfType(panel, ActiveListView::class.java)!! } + edt { + assertTrue(view.select(item.id)) + controller.rename(item, "renamed", onFailure = {}) + } + flush() + + assertEquals(item.id, edt { view.selected()?.key }) + assertEquals("renamed", edt { (view.selected() as ActiveListItem).title }) + } + fun `test the current and pending rows are not draggable`() { rpc.listed += main() rpc.listed += worktree("aardvark") diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt index 57c7d6ea8a80..1518f5fdc72d 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt @@ -52,6 +52,20 @@ class ActiveListReorderTest : BasePlatformTestCase() { assertEquals(listOf("cur", "c", "a", "b"), move.keys) } + fun `test drop anchors the moved row for owner refresh`() { + val moves = mutableListOf() + val view = view(moves) + view.update(sectioned()) + layout(view) + + assertTrue(view.select("c")) + view.over("c", center(view, 1)) + view.drop() + view.update(sectioned().let { listOf(it[0], it[3], it[1], it[2]) }) + + assertEquals("c", view.selected()?.key) + } + fun `test drag cannot leave its section and never displaces the current row`() { val moves = mutableListOf() val view = view(moves) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt new file mode 100644 index 000000000000..5beac7964740 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt @@ -0,0 +1,135 @@ +package ai.kilocode.client.ui.list + +import com.intellij.testFramework.fixtures.BasePlatformTestCase + +class ActiveListSelectionTest : BasePlatformTestCase() { + + fun `test two phase rebuild keeps selection and mutes onSelect`() { + var calls = 0 + val view = view { calls++ } + view.update(rows("a", "b", "c")) + calls = 0 + assertTrue(view.select("b")) + assertEquals(1, calls) + calls = 0 + + view.update(rows("a", "c")) + view.update(rows("a", "b", "c")) + + assertEquals("b", view.selected()?.key) + assertEquals(0, calls) + } + + fun `test preserve keeps absent anchor pending`() { + val view = view() + view.update(rows("a", "b")) + assertTrue(view.select("b")) + + view.update(rows("a"), ActiveListSelection.Preserve) + assertNull(view.selected()) + view.update(rows("a", "b"), ActiveListSelection.Preserve) + + assertEquals("b", view.selected()?.key) + } + + fun `test stable key preserves selection when value changes`() { + val view = view() + view.update(listOf(row("a", "Alpha"), row("b", "Beta"))) + assertTrue(view.select("b")) + + view.update(listOf(row("a", "Alpha"), row("b", "Beta changed"))) + + assertEquals("b", view.selected()?.key) + assertEquals("Beta changed", view.selected()?.title) + } + + fun `test slide selects row that took selected slot`() { + val view = view() + view.update(rows("a", "b", "c")) + assertTrue(view.select("b")) + + view.update(rows("a", "c"), ActiveListSelection.Slide) + assertEquals("c", view.selected()?.key) + + view.update(emptyList(), ActiveListSelection.Slide) + assertNull(view.selected()) + } + + fun `test slide clears when nothing was selected`() { + val view = view() + view.update(rows("a", "b")) + view.clearSelection() + + view.update(rows("a"), ActiveListSelection.Slide) + + assertNull(view.selected()) + } + + fun `test filter selects first match and clearing restores anchor`() { + val view = view() + view.update(rows("a", "b", "c")) + assertTrue(view.select("b")) + + view.filter("Alpha") + assertEquals("a", view.selected()?.key) + view.filter("") + + assertEquals("b", view.selected()?.key) + } + + fun `test multi select restores all surviving rows`() { + val view = ActiveListView("", ActiveListConfig(selection = javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)) { _, _ -> } + view.update(rows("a", "b", "c", "d")) + view.setSelectionIndices(intArrayOf(1, 3)) + + view.update(rows("a", "b", "c", "d")) + assertEquals(listOf("b", "d"), view.selectedKeys()) + view.update(rows("a", "b", "c")) + + assertEquals(listOf("b"), view.selectedKeys()) + } + + fun `test absent select creates pending anchor`() { + val view = view() + view.update(rows("a")) + + assertFalse(view.select("b")) + assertNull(view.selected()) + view.update(rows("a", "b")) + + assertEquals("b", view.selected()?.key) + } + + fun `test identity override restores by identity and key`() { + val view = view() + view.update(listOf(row("pending", "Pending", "same"))) + assertTrue(view.select("pending")) + view.update(listOf(row("created", "Created", "same"))) + assertEquals("created", view.selected()?.key) + + assertTrue(view.select("created")) + view.update(listOf(row("created", "Created again", "other"))) + assertEquals("created", view.selected()?.key) + } + + private fun view(onSelect: () -> Unit = {}): ActiveListView { + return ActiveListView("") { _, _ -> }.apply { this.onSelect = onSelect } + } + + private fun rows(vararg keys: String): List = keys.map { row(it, title(it)) } + + private fun row(key: String, title: String, identity: Any = key): ActiveListItem = object : ActiveListItem { + override val key = key + override val identity = identity + override val title = title + override val search = title + } + + private fun title(key: String): String = when (key) { + "a" -> "Alpha" + "b" -> "Beta" + "c" -> "Gamma" + "d" -> "Delta" + else -> key + } +} From 63766299125607313074230a174036b11239e256 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 12:50:07 -0400 Subject: [PATCH 11/30] fix(jetbrains): size the drag gap to the row body A row that opens a section paints the section header band inside its own cell, so capturing the drag placeholder height from getCellBounds folded that band in. The gap then rendered a band taller than the row, and because the equal-height pass measures the gap like any other row, every row stretched to that inflated height. Measure the row body instead, which is also what the floating drag image paints. --- .../kilocode/client/ui/list/ActiveListView.kt | 7 +++- .../client/ui/list/ActiveListReorderTest.kt | 37 ++++++++++++++++++- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt index 84d7002e2d8c..a64e4c43fcc9 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt @@ -638,8 +638,11 @@ internal class ActiveListView( cancel() return } - val bounds = list.getCellBounds(from, from) - val state = current ?: Drag(key, from, from, bounds?.height ?: list.fixedCellHeight.takeIf { it > 0 } ?: renderer.bodyPreferredHeight(list, base[from], from, true, true)) + // Measure the row body, not the whole cell: a row that opens a section renders the header + // band inside its own cell, and folding that band into the gap height both oversizes the + // placeholder and — through the equal-height pass, which measures the gap like any other + // row — stretches every row to the header-carrying cell's height. + val state = current ?: Drag(key, from, from, renderer.bodyPreferredHeight(list, base[from], from, true, true)) if (current == null) { press = null setHovered(-1) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt index 1518f5fdc72d..e72a354c622a 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt @@ -134,6 +134,33 @@ class ActiveListReorderTest : BasePlatformTestCase() { assertTrue(-image.second.y <= image.first.getHeight(null)) } + fun `test dragging the row that opens a section keeps every row height`() { + val view = view(mutableListOf()) + view.update(sectioned()) + layout(view) + val before = heights(view) + + // Row 1 opens the "wt" section, so its cell paints the section band above its body. + view.over("a", center(view, 2)) + layout(view) + + // The band belongs to the slot, not the dragged row: the gap takes a body-sized slot and no + // row grows to the band-inclusive height of the cell the drag started from. + assertEquals(before, heights(view)) + } + + fun `test the gap keeps the dragged row body height when rows size to content`() { + val view = view(mutableListOf(), ActiveListConfig.Preferred) + view.update(sectioned()) + layout(view) + val body = heights(view)[2] + + view.over("a", center(view, 2)) + layout(view) + + assertEquals(body, heights(view)[2]) + } + fun `test grabbing a section header row still anchors inside the body image`() { val view = view(mutableListOf()) view.update(sectioned()) @@ -145,9 +172,13 @@ class ActiveListReorderTest : BasePlatformTestCase() { assertEquals(0, image.second.y) } - private fun view(moves: MutableList): ActiveListView { + private fun view( + moves: MutableList, + cfg: ActiveListConfig = ActiveListConfig.Equal, + ): ActiveListView { return ActiveListView( empty = "", + cfg = cfg, reorder = ActiveListReorder( movable = { it.section != null }, onMove = { moves += it }, @@ -168,6 +199,10 @@ class ActiveListReorderTest : BasePlatformTestCase() { return (0 until view.list.model.size).map { view.list.model.getElementAt(it) } } + private fun heights(view: ActiveListView): List { + return (0 until view.list.model.size).map { view.list.getCellBounds(it, it)!!.height } + } + private fun center(view: ActiveListView, index: Int): Point { val bounds: Rectangle = view.list.getCellBounds(index, index) ?: error("no bounds for $index") return Point(bounds.x + 8, bounds.y + bounds.height / 2) From 092214b11ccd7dd4dc355052dbb3f75b33cd2446 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 13:00:42 -0400 Subject: [PATCH 12/30] fix(jetbrains): paint the whole row body into the drag image rowImage translated the graphics by the body's offset inside the cell before calling wrap.paint(). paint() already maps the graphics origin to the component's own top-left, so the offset was applied twice. On rows that do not open a section the offset is zero and nothing looked wrong, but on a row that carries the section header band the copy was shifted up by the band height, leaving the dragged row sliced off at the top and the rest of the image blank. --- .../client/ui/list/ActiveListRenderer.kt | 5 +++- .../client/ui/list/ActiveListReorderTest.kt | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt index 1bed3a9390d0..10511db6e618 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt @@ -333,7 +333,10 @@ internal class ActiveListRenderer( val g2 = image.createGraphics() try { g2.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f) - g2.translate(-wrap.x, -wrap.y) + // paint() already treats the graphics origin as the body's own top-left, so the body's + // offset inside the cell must not be applied again: on a row that opens a section that + // offset is the header band, and shifting by it would lift the copy off the image and + // leave most of it blank. wrap.paint(g2) } finally { g2.dispose() diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt index e72a354c622a..a04269cb12fe 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt @@ -2,8 +2,10 @@ package ai.kilocode.client.ui.list import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.ui.UIUtil +import java.awt.Image import java.awt.Point import java.awt.Rectangle +import java.awt.image.BufferedImage class ActiveListReorderTest : BasePlatformTestCase() { @@ -172,6 +174,21 @@ class ActiveListReorderTest : BasePlatformTestCase() { assertEquals(0, image.second.y) } + fun `test the drag image of a section header row paints its whole body`() { + val view = view(mutableListOf()) + view.update(sectioned()) + layout(view) + + // Row 1 opens the "wt" section, so its body starts below the band inside its own cell. The + // copy still covers the body edge to edge: nothing is shifted off the image. + val header = view.dragImage(center(view, 1))?.first ?: error("expected a drag image") + val plain = view.dragImage(center(view, 2))?.first ?: error("expected a drag image") + + assertEquals(0, blank(header)) + assertEquals(blank(plain), blank(header)) + assertEquals(plain.getHeight(null), header.getHeight(null)) + } + private fun view( moves: MutableList, cfg: ActiveListConfig = ActiveListConfig.Equal, @@ -199,6 +216,14 @@ class ActiveListReorderTest : BasePlatformTestCase() { return (0 until view.list.model.size).map { view.list.model.getElementAt(it) } } + /** Rows of the image that are fully transparent, i.e. left unpainted. */ + private fun blank(image: Image): Int { + val pixels = image as BufferedImage + return (0 until pixels.height).count { y -> + (0 until pixels.width).all { x -> (pixels.getRGB(x, y) ushr 24) == 0 } + } + } + private fun heights(view: ActiveListView): List { return (0 until view.list.model.size).map { view.list.getCellBounds(it, it)!!.height } } From f60e8dc84165fc4bbdd13a04218265fdb13da545 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 13:42:20 -0400 Subject: [PATCH 13/30] refactor(jetbrains): route every list refresh through one selection policy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four call sites still rebuilt their list with ActiveListSelection.Index(selectedIndex()), a hand-rolled Slide that pinned the old slot even when the selected row survived at a new index — McpSettingsUi.edit could therefore land on a different server whenever the reload reordered rows. Replace them with Slide, or Key where the mutated row is known, and delete the helper and the Index policy behind them. Scrolling was a policy case too (PreserveNoScroll), which meant a plain refresh dragged the viewport back to the selection on every status poll. Scroll from sync() only when the refresh actually moved the selection, which collapses Preserve/PreserveNoScroll into one policy and leaves the viewport alone while rows are merely re-found. Also fold the remaining duplicates into the shared path: WorktreeSessionEditorPanel names the shown session with Key instead of update-then-select, HistoryPanel drops its private restore wrapper and its copy of move() (which stepped over unfiltered rows), and move() now treats an empty selection as starting past the near end. --- .../jetbrains-list-refresh-selection.md | 5 + .../client/agentManager/AgentManagerPanel.kt | 2 +- .../worktree/WorktreeSessionEditorPanel.kt | 14 +-- .../client/session/history/HistoryPanel.kt | 23 +--- .../client/settings/agents/McpConfigurable.kt | 4 +- .../settings/agents/SkillsConfigurable.kt | 2 +- .../settings/base/SettingsInlineListPanel.kt | 2 +- .../client/settings/base/SettingsListPanel.kt | 6 -- .../settings/context/ContextSettingsUi.kt | 6 ++ .../settings/providers/ProvidersSettingsUi.kt | 2 +- .../client/settings/rules/RulesSettingsUi.kt | 2 +- .../ai/kilocode/client/ui/list/ActiveList.kt | 4 + .../kilocode/client/ui/list/ActiveListView.kt | 67 +++++++----- .../kilocode/client/ui/picker/PickerPopup.kt | 5 + .../settings/agents/McpSettingsUiTest.kt | 25 +++++ .../settings/agents/SkillsSettingsUiTest.kt | 11 ++ .../settings/base/SettingsListViewTest.kt | 15 +-- .../settings/rules/RulesSettingsUiTest.kt | 13 +++ .../client/ui/list/ActiveListSelectionTest.kt | 100 ++++++++++++++++++ 19 files changed, 227 insertions(+), 81 deletions(-) create mode 100644 .changeset/jetbrains-list-refresh-selection.md diff --git a/.changeset/jetbrains-list-refresh-selection.md b/.changeset/jetbrains-list-refresh-selection.md new file mode 100644 index 000000000000..ba5201a09e11 --- /dev/null +++ b/.changeset/jetbrains-list-refresh-selection.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Keep settings, history, and session lists on the same row and scroll position when they refresh, and select the neighbouring row after a delete. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 5b7f2578793b..464cb7cc6a42 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -374,7 +374,7 @@ class AgentManagerPanel( pull, ) }, - ActiveListSelection.PreserveNoScroll, + ActiveListSelection.Preserve, ) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt index 779cec131fbd..7693b836d813 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt @@ -126,7 +126,7 @@ class WorktreeSessionEditorPanel( addToCenter(splitter) syncExpanded(KiloPluginSettings.getWorktreeSessionListExpanded()) bindModel() - manager.onPresent = { key -> select(key) } + manager.onPresent = { key -> key?.let { list.select(it) } } manager.onListChanged = { sync() project?.service()?.refreshStats() @@ -407,14 +407,10 @@ class WorktreeSessionEditorPanel( if (pending || key == SessionHost.NEW) rows += NewRow rows += HistoryTime.sorted(controller.sessions().map { LocalHistoryItem(it) }) .map { SessionRow(it.session, kinds[it.id], deleting = it.id in deleting, live = titles[it.id]) } - list.update(rows, ActiveListSelection.PreserveNoScroll) - select(if (pending) SessionHost.NEW else key) - } - - @RequiresEdt - private fun select(key: String?) { - if (key == null) return - list.select(key) + // The host owns which session is shown, so it also owns the selection: name the row and let + // the list hold that key until a refresh brings it in. + val shown = if (pending) SessionHost.NEW else key + list.update(rows, shown?.let { ActiveListSelection.Key(it) } ?: ActiveListSelection.Preserve) } @RequiresEdt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryPanel.kt index 06f793e782ff..a9be9aba4985 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryPanel.kt @@ -274,19 +274,8 @@ class HistoryPanel( private fun syncRows() { localRows = localHistoryRows(controller.local.visibleItems, snapshot, controller::deleting) cloudRows = cloudHistoryRows(controller.cloud.visibleItems, snapshot) - restore(localList, localRows) - restore(cloudList, cloudRows) - } - - /** - * Rebuilds [list] while keeping selection stable. Surviving selected rows stay selected; when a - * selected row disappears (e.g. it was just deleted) selection slides to the row that took its - * slot — the following row, or the last row when the removed one was last — so the highlight - * moves naturally instead of vanishing. Selection clears only when nothing was selected or the - * list is now empty. - */ - private fun restore(list: ActiveList, rows: List) { - list.update(rows, ActiveListSelection.Slide) + localList.update(localRows, ActiveListSelection.Slide) + cloudList.update(cloudRows, ActiveListSelection.Slide) } @RequiresEdt @@ -465,13 +454,7 @@ class HistoryPanel( private fun activeInfo(): TabInfo = if (tabs.selectedInfo === cloudInfo) cloudInfo else localInfo - private fun move(step: Int) { - val size = itemCount() - if (size <= 0) return - val cur = selectedIndex().takeIf { it >= 0 } ?: if (step > 0) -1 else size - val idx = (cur + step).coerceIn(0, size - 1) - activeList().selectIndex(idx) - } + private fun move(step: Int) = activeList().move(step) override fun dispose() { timer.stop() diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/McpConfigurable.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/McpConfigurable.kt index 10a06fb8283d..2a966470a9d7 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/McpConfigurable.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/McpConfigurable.kt @@ -147,7 +147,7 @@ internal class McpSettingsUi( val dialog = create(name, server.config) if (!dialog.showAndGet()) return val next = dialog.result() - mutateAndReload(selectionIndex()) { + mutateAndReload(ActiveListSelection.Key(name)) { if (!service().saveMcp(dir, name, server.scope, next)) { throw SettingsMessageException(KiloBundle.message("settings.agentBehavior.save.failed")) } @@ -165,7 +165,7 @@ internal class McpSettingsUi( ) if (result != Messages.YES) return val scope = servers[name]?.scope ?: return - mutateAndReload(selectionIndex()) { + mutateAndReload(ActiveListSelection.Slide) { if (!service().saveMcp(dir, name, scope, null)) { throw SettingsMessageException(KiloBundle.message("settings.agentBehavior.save.failed")) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/SkillsConfigurable.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/SkillsConfigurable.kt index 61802cabe712..7a2694bb2594 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/SkillsConfigurable.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/SkillsConfigurable.kt @@ -283,7 +283,7 @@ internal class SkillsSettingsUi( ) if (result != Messages.YES) return state.update { copy(deleted = deleted + skill.location, edited = edited - skill.location) } - view.update(rows(), selectionIndex()) + view.update(rows(), ActiveListSelection.Slide) } private fun content(skill: SkillDto) = draft.edited[skill.location] ?: skill.content diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsInlineListPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsInlineListPanel.kt index fc07d2c4a765..76972c669f32 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsInlineListPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsInlineListPanel.kt @@ -80,7 +80,7 @@ internal abstract class SettingsInlineListPanel( fun setItems(items: List, enabled: Boolean) { checkEdt() setEnabled(enabled) - view.update(items, ActiveListSelection.PreserveNoScroll) + view.update(items, ActiveListSelection.Preserve) toolbar?.updateActionsImmediately() } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsListPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsListPanel.kt index 1e4dda9f9d49..bdb25581ebe8 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsListPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/base/SettingsListPanel.kt @@ -140,12 +140,6 @@ internal abstract class SettingsListPanel( protected open fun afterApply() = Unit - @RequiresEdt - protected fun selectionIndex(): ActiveListSelection { - checkEdt() - return ActiveListSelection.Index(view.selectedIndex()) - } - private fun header(): JComponent { search.textEditor.registerKeyboardAction( { view.primary() }, diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/context/ContextSettingsUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/context/ContextSettingsUi.kt index 8b156065b829..e03a6adc5525 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/context/ContextSettingsUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/context/ContextSettingsUi.kt @@ -254,6 +254,12 @@ private class NumberFilter : DocumentFilter() { } } +/** + * Plain string list with add/edit/remove. Rows carry no keys, cells, badges, or sections and every + * mutation happens locally in this component, so it stays on [CollectionListModel] instead of + * [ai.kilocode.client.ui.list.ActiveListView], whose value is restoring selection across refreshes + * driven from elsewhere. + */ internal class PatternList( private val change: (List) -> Unit, ) : Stack(StackAxis.VERTICAL, UiStyle.Gap.sm()) { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUi.kt index e509e97a765a..22e134b49d5c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/providers/ProvidersSettingsUi.kt @@ -507,7 +507,7 @@ internal class ProvidersContent( ProvidersSettingsUi.LOG.info("provider settings content update: start providers=${state.providers.size} connected=${state.connected.size} disabled=${state.disabled.size} descriptions=$notes") this.state = state val rows = providerListRows(state, "", disabledRows = busy) - if (select != null) view.update(rows, ActiveListSelection.Key(select)) else view.update(rows) + view.update(rows, select?.let { ActiveListSelection.Key(it) } ?: ActiveListSelection.Preserve) ProvidersSettingsUi.LOG.info("provider settings content update: completed rows=${rows.size}") } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/rules/RulesSettingsUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/rules/RulesSettingsUi.kt index c234a08b9767..71483f226b6d 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/rules/RulesSettingsUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/rules/RulesSettingsUi.kt @@ -198,7 +198,7 @@ internal class RulesSettingsUi( ) if (result != Messages.YES) return state.update { copy(instructions = instructions - path, edited = edited - path) } - view.update(rows(), selectionIndex()) + view.update(rows(), ActiveListSelection.Slide) } private fun open(path: String) { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt index e266dbde6098..144e10794ae6 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt @@ -95,6 +95,10 @@ internal class ActiveList( @RequiresEdt fun selectIndex(index: Int) = view.selectIndex(index) + /** Steps the selection by [step] visible rows, clamped to the ends of the list. */ + @RequiresEdt + fun move(step: Int) = view.move(step) + @RequiresEdt fun selectedIndex(): Int = view.selectedIndex() diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt index a64e4c43fcc9..bb7cd3ae5057 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt @@ -321,17 +321,14 @@ internal class ActiveListView( checkEdt() if (this.items != items) heightKey = null this.items = items - val scroll = selection != ActiveListSelection.PreserveNoScroll when (selection) { is ActiveListSelection.Key -> { anchor = setOf(selection.key) mark = -1 - sync(Absent.KEEP, scroll) + sync(Absent.KEEP) } - is ActiveListSelection.Index -> sync(Absent.KEEP, scroll, selection.index, reanchor = true) - ActiveListSelection.Slide -> sync(Absent.SLIDE, scroll) - ActiveListSelection.PreserveNoScroll, - ActiveListSelection.Preserve -> sync(Absent.KEEP, scroll) + ActiveListSelection.Slide -> sync(Absent.SLIDE) + ActiveListSelection.Preserve -> sync(Absent.KEEP) } } @@ -366,13 +363,14 @@ internal class ActiveListView( } @RequiresEdt - private fun sync(absent: Absent = Absent.KEEP, scroll: Boolean = true, at: Int? = null, reanchor: Boolean = false) { + private fun sync(absent: Absent = Absent.KEEP, at: Int? = null) { checkEdt() val q = filter.trim() val base = if (q.isBlank()) items else items.filter { matcher(q, it) } val state = drag if (state != null && base.none { it.key == state.key }) drag = null val rows = drag?.let { activeListGapRows(base, it.key, it.index, it.height) } ?: base + val before = identities() restoring = true try { // Rebuilding the model fires a list-wide repaint, so skip it when the visible rows are @@ -383,33 +381,38 @@ internal class ActiveListView( model.replaceAll(rows) } syncCellHeight(rows) - restore(rows, absent, scroll, at, reanchor) + restore(rows, absent, at) + // Scroll only when the refresh moved the selection to another row. Re-finding the same + // rows must leave the viewport where the user left it, or a polling owner would drag the + // view back to the selection on every tick. + val idx = list.selectedIndex + if (idx >= 0 && identities() != before) ScrollingUtil.ensureIndexIsVisible(list, idx, 0) } finally { restoring = false } } + /** + * Reselects the anchored rows in the rebuilt [rows], or the row [at] when the drag gap pins the + * slot. Falls back to [absent] once none of the anchored rows survive. + */ @RequiresEdt - private fun restore(rows: List, absent: Absent, scroll: Boolean, at: Int?, reanchor: Boolean) { + private fun restore(rows: List, absent: Absent, at: Int?) { checkEdt() val idx = at?.let { activeListIndex(rows, it) }?.takeIf { it >= 0 } if (idx != null) { - choose(idx, scroll) + list.selectedIndex = idx mark = idx - if (reanchor) anchor = setOf(rows[idx].identity) return } val indices = anchor.mapNotNull { id -> activeListIdentityIndex(rows, id).takeIf { it >= 0 } } if (indices.isNotEmpty()) { list.selectedIndices = indices.toIntArray() - mark = indices.first() - if (scroll) ScrollingUtil.ensureIndexIsVisible(list, mark, 0) + mark = indices.min() return } when (absent) { - Absent.KEEP -> { - list.clearSelection() - } + Absent.KEEP -> list.clearSelection() Absent.SLIDE -> { if (anchor.isEmpty() || rows.isEmpty()) { list.clearSelection() @@ -417,7 +420,7 @@ internal class ActiveListView( return } val next = mark.coerceIn(0, rows.lastIndex) - choose(next, scroll) + list.selectedIndex = next anchor = setOf(rows[next].identity) mark = next } @@ -426,7 +429,7 @@ internal class ActiveListView( list.clearSelection() return } - choose(0, scroll) + list.selectedIndex = 0 mark = 0 if (anchor.isEmpty()) anchor = setOf(rows[0].identity) } @@ -498,8 +501,10 @@ internal class ActiveListView( checkEdt() val size = model.size if (size <= 0) return - val idx = ((list.selectedIndex.takeIf { it >= 0 } ?: 0) + step).coerceIn(0, size - 1) - choose(idx) + // With nothing selected the first step lands on the near end: down takes the first row, up + // takes the last, instead of skipping past it. + val from = list.selectedIndex.takeIf { it >= 0 } ?: if (step > 0) -1 else size + choose((from + step).coerceIn(0, size - 1)) } @RequiresEdt @@ -654,7 +659,7 @@ internal class ActiveListView( val next = idx.coerceIn(run.first, run.last) if (state.index == next && current != null) return drag = state.copy(index = next) - sync(Absent.KEEP, scroll = false, at = next) + sync(at = next) } @RequiresEdt @@ -675,7 +680,7 @@ internal class ActiveListView( heightKey = null anchor = setOf(state.key) mark = target - sync(Absent.KEEP, scroll = false, at = target) + sync(at = target) if (source == target) return reorder?.onMove?.invoke(ActiveListMove(state.key, source, target, rows.map { it.key })) } @@ -886,14 +891,24 @@ private fun activeListIndex(items: List, index: Int): Int { return index.coerceIn(0, items.lastIndex) } +/** + * What a refresh should do with the selection. Every policy keeps the rows the user last selected + * when they survive the refresh, and none of them scrolls in that case; they differ only in what + * happens once those rows are gone. + */ internal sealed interface ActiveListSelection { - /** Restore the remembered rows and scroll to them; select nothing while they are absent. */ + /** Select nothing while the remembered rows are absent, and pick them up again if they return. */ data object Preserve : ActiveListSelection - data object PreserveNoScroll : ActiveListSelection - /** Restore the remembered rows; when they are all gone, select the row that took their slot. */ + + /** + * Select the row that took the remembered row's slot — the following row, or the last row when + * the removed one was last — so a deletion moves the highlight instead of dropping it. Clears + * only when nothing was selected or the list is now empty. + */ data object Slide : ActiveListSelection + + /** Select [key] instead, now or as soon as a later refresh brings that row in. */ data class Key(val key: String) : ActiveListSelection - data class Index(val index: Int) : ActiveListSelection } internal fun activeListMatches(query: String, item: ActiveListItem): Boolean { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/picker/PickerPopup.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/picker/PickerPopup.kt index 2d3c8c38fea4..0f7395d28520 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/picker/PickerPopup.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/picker/PickerPopup.kt @@ -173,6 +173,11 @@ internal class PickerPopup( return popup } + /** + * Rebuilds the rows and restores the highlight. Unlike [ai.kilocode.client.ui.list.ActiveListView], + * which leaves the selection empty when the remembered row is gone, a picker must always offer a + * candidate to accept, so this falls back to the first row. + */ fun refresh(prefer: Any? = selectedKey(), at: Int? = null) { val data = rows(field?.text.orEmpty()) model.replaceAll(data) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/McpSettingsUiTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/McpSettingsUiTest.kt index aa4a216ee308..4b78fa943d06 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/McpSettingsUiTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/McpSettingsUiTest.kt @@ -170,6 +170,31 @@ class McpSettingsUiTest : BasePlatformTestCase() { assertNull(save.third) } + fun `test remove selects the server that took the deleted slot`() { + val panel = panel() + flushUntil { rows(panel).size == 3 } + agentRpc.mcps = agentRpc.mcps.filterNot { it.name == "filesystem" } + TestDialogManager.setTestDialog(TestDialog.YES) + + click(panel, "filesystem", "remove") + + flushUntil { rows(panel).none { it.key == "filesystem" } } + assertEquals("github", edt { list(panel).selectedValue?.key }) + } + + fun `test edit keeps the edited server selected when the reload reorders rows`() { + val next = McpConfigDto(type = "local", command = listOf("bun", "new-server")) + val panel = panel { name, cfg -> FakeEditDialog(name, cfg, next) } + flushUntil { rows(panel).size == 3 } + // Sorts above the edited server, so the reload shifts every row down one slot. + agentRpc.mcps = agentRpc.mcps + McpStatusDto("alpha", "failed") + + click(panel, "filesystem", "edit") + + flushUntil { rows(panel).size == 4 } + assertEquals("filesystem", edt { list(panel).selectedValue?.key }) + } + fun `test remove action requires confirmation`() { val panel = panel() flushUntil { rows(panel).size == 3 } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/SkillsSettingsUiTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/SkillsSettingsUiTest.kt index b6448a4b11f3..ce2e6c37152e 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/SkillsSettingsUiTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/SkillsSettingsUiTest.kt @@ -274,6 +274,17 @@ class SkillsSettingsUiTest : BasePlatformTestCase() { assertEquals(listOf(DIR to CUSTOM), agentRpc.skillRemovals) } + fun `test delete selects the skill that took the deleted slot`() { + val panel = panel() + flushUntil { rows(panel).size == 3 } + val next = edt { rows(panel)[1].key } + TestDialogManager.setTestDialog(TestDialog.YES) + + click(skillsList(panel), panel, CUSTOM, "delete") + + assertEquals(next, edt { skillsList(panel).selectedValue?.key }) + } + fun `test delete action requires confirmation`() { val panel = panel() flushUntil { rows(panel).size == 3 } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt index e05a97cab5bb..c7101e0611de 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt @@ -767,7 +767,7 @@ class SettingsListViewTest : BasePlatformTestCase() { } } - fun `test preserve no scroll keeps scroll position after row change`() { + fun `test refresh keeps scroll position after row change`() { edt { val view = ActiveListView("Empty") { _, _ -> } val rows = (0 until 30).map { item("row$it", "Row $it", null, ActiveListCell("level", "Allow", alwaysVisible = true)) } @@ -785,7 +785,7 @@ class SettingsListViewTest : BasePlatformTestCase() { val before = scroll.viewport.viewPosition.y assertTrue("expected a scrolled viewport", before > 0) - view.update(rows, ActiveListSelection.PreserveNoScroll) + view.update(rows, ActiveListSelection.Preserve) UIUtil.dispatchAllInvocationEvents() assertEquals(before, scroll.viewport.viewPosition.y) @@ -806,17 +806,6 @@ class SettingsListViewTest : BasePlatformTestCase() { } } - fun `test update selects preferred index`() { - edt { - val view = ActiveListView("Empty") { _, _ -> } - view.update(listOf(item("a", "Alpha", null), item("b", "Beta", null), item("c", "Gamma", null))) - view.list.selectedIndex = 1 - view.update(listOf(item("a", "Alpha", null), item("c", "Gamma", null)), ActiveListSelection.Index(1)) - - assertEquals("c", view.selected()?.key) - } - } - fun `test list view tracks viewport width`() { edt { val view = ActiveListView("Empty") { _, _ -> } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/rules/RulesSettingsUiTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/rules/RulesSettingsUiTest.kt index c4f9a77d6f02..b72995256ed4 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/rules/RulesSettingsUiTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/rules/RulesSettingsUiTest.kt @@ -188,6 +188,19 @@ class RulesSettingsUiTest : BasePlatformTestCase() { assertEquals(emptyList(), rpc.configPatches.single().instructions) } + fun `test delete selects the rule that took the deleted slot`() { + val panel = panel(input = { "./EXTRA.md" }) + flushUntil { rows(panel).size == 1 } + edt { panel.addFile() } + flushUntil { rows(panel).size == 2 } + TestDialogManager.setTestDialog(TestDialog.YES) + + click(rulesList(panel), panel, "./RULES.md", "delete") + + assertEquals(listOf("./EXTRA.md"), edt { rows(panel).map { it.key } }) + assertEquals("./EXTRA.md", edt { rulesList(panel).selectedValue?.key }) + } + fun `test delete action requires confirmation`() { val panel = panel() flushUntil { rows(panel).size == 1 } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt index 5beac7964740..b2daca705feb 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt @@ -1,6 +1,9 @@ package ai.kilocode.client.ui.list import com.intellij.testFramework.fixtures.BasePlatformTestCase +import com.intellij.ui.components.JBScrollPane +import com.intellij.util.ui.UIUtil +import java.awt.Dimension class ActiveListSelectionTest : BasePlatformTestCase() { @@ -89,6 +92,75 @@ class ActiveListSelectionTest : BasePlatformTestCase() { assertEquals(listOf("b"), view.selectedKeys()) } + fun `test key policy keeps an absent row pending`() { + val view = view() + view.update(rows("a", "b")) + + view.update(rows("a"), ActiveListSelection.Key("b")) + assertNull(view.selected()) + view.update(rows("a", "b"), ActiveListSelection.Preserve) + + assertEquals("b", view.selected()?.key) + } + + fun `test clearing selection drops the anchor`() { + val view = view() + view.update(rows("a", "b")) + assertTrue(view.select("b")) + + view.clearSelection() + view.update(rows("a", "b")) + + assertNull(view.selected()) + } + + fun `test slide keeps the last row selected when it is removed`() { + val view = view() + view.update(rows("a", "b", "c")) + assertTrue(view.select("c")) + + view.update(rows("a", "b"), ActiveListSelection.Slide) + + assertEquals("b", view.selected()?.key) + } + + fun `test move steps the selection and a refresh keeps the moved row`() { + val view = view() + view.update(rows("a", "b", "c")) + assertNull(view.selected()) + + // From no selection the first step lands on the near end rather than skipping it. + view.move(1) + assertEquals("a", view.selected()?.key) + view.clearSelection() + view.move(-1) + assertEquals("c", view.selected()?.key) + + view.selectIndex(0) + view.move(1) + assertEquals("b", view.selected()?.key) + view.update(rows("a", "b", "c")) + assertEquals("b", view.selected()?.key) + + view.move(-5) + assertEquals("a", view.selected()?.key) + view.move(9) + assertEquals("c", view.selected()?.key) + } + + fun `test refresh while filtered restores the anchored row`() { + val view = view() + view.update(rows("a", "b", "c")) + assertTrue(view.select("b")) + view.filter("Beta") + assertEquals("b", view.selected()?.key) + + view.update(rows("a", "b", "c", "d")) + + assertEquals(listOf("b"), view.selectedKeys()) + assertEquals(1, view.list.model.size) + } + fun `test absent select creates pending anchor`() { val view = view() view.update(rows("a")) @@ -100,6 +172,34 @@ class ActiveListSelectionTest : BasePlatformTestCase() { assertEquals("b", view.selected()?.key) } + fun `test refresh keeps the viewport and only a moved selection scrolls`() { + val view = view() + val rows = (0 until 30).map { row("k$it", "Row $it") } + view.update(rows) + val scroll = JBScrollPane(view.list) + scroll.size = Dimension(320, 80) + scroll.doLayout() + view.list.doLayout() + UIUtil.dispatchAllInvocationEvents() + + assertTrue(view.select("k25")) + scroll.doLayout() + UIUtil.dispatchAllInvocationEvents() + val before = scroll.viewport.viewPosition.y + assertTrue("expected a scrolled viewport", before > 0) + + // Re-finding the same row must not drag the viewport back to the selection. + view.update(rows) + UIUtil.dispatchAllInvocationEvents() + assertEquals(before, scroll.viewport.viewPosition.y) + + view.update(rows, ActiveListSelection.Key("k0")) + UIUtil.dispatchAllInvocationEvents() + + assertEquals("k0", view.selected()?.key) + assertTrue(scroll.viewport.viewPosition.y < before) + } + fun `test identity override restores by identity and key`() { val view = view() view.update(listOf(row("pending", "Pending", "same"))) From e8e4602ae4737e63cb71ebfc49724a9b1dba6f43 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 14:08:08 -0400 Subject: [PATCH 14/30] test(jetbrains): load real icons in the worktree icon size test The platform resolves every svg-backed icon to a 1x1 placeholder when GraphicsEnvironment.isHeadless(), which is how CI runs but not how the tests run locally on macOS. The test compared those placeholder widths against the custom-painted activity icons, so it passed locally and failed CI with expected:<1> but was:<16>. Turn real loading on for the assertions with IconLoader.activate(), the platform's TestOnly hook for exactly this, and restore the ambient state afterwards. Tighten the load assertions to > 1 so the placeholder can no longer satisfy them. Verified by forcing -Djava.awt.headless=true on the frontend test JVM: the test fails before this change and the whole frontend suite passes after it. --- .../agentManager/WorktreeControllerTest.kt | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt index 176a4e8579da..9de9cc52dad2 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt @@ -19,7 +19,9 @@ import ai.kilocode.rpc.dto.SessionActivityKindDto import ai.kilocode.rpc.dto.WorktreeDto import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service +import com.intellij.openapi.util.IconLoader import com.intellij.testFramework.fixtures.BasePlatformTestCase +import java.awt.GraphicsEnvironment import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch @@ -371,13 +373,20 @@ class WorktreeControllerTest : BasePlatformTestCase() { } fun `test worktree icons load at the same size`() { - assertTrue("branch icon should load", WorktreeIcons.branch.iconWidth > 0) - assertTrue("lock icon should load", WorktreeIcons.locked.iconWidth > 0) - assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.locked.iconWidth) - assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.locked.iconHeight) - for (kind in SessionActivityKind.entries) { - assertEquals(WorktreeIcons.branch.iconWidth, kind.icon().iconWidth) - assertEquals(WorktreeIcons.branch.iconHeight, kind.icon().iconHeight) + // Loading an svg asset resolves to a 1x1 placeholder while the platform is headless, which is + // how CI runs, so switch real loading on for the assertions and put the ambient state back. + IconLoader.activate() + try { + assertTrue("branch icon should load", WorktreeIcons.branch.iconWidth > 1) + assertTrue("lock icon should load", WorktreeIcons.locked.iconWidth > 1) + assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.locked.iconWidth) + assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.locked.iconHeight) + for (kind in SessionActivityKind.entries) { + assertEquals(WorktreeIcons.branch.iconWidth, kind.icon().iconWidth) + assertEquals(WorktreeIcons.branch.iconHeight, kind.icon().iconHeight) + } + } finally { + if (GraphicsEnvironment.isHeadless()) IconLoader.deactivate() } } From ccc6b520349f296e1c3bd87164ad0c1b83774674 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 14:37:26 -0400 Subject: [PATCH 15/30] refactor(jetbrains): slide workflow selection after delete The workflows page landed on main while selectionIndex() was being removed here, so the merge left it calling a helper that no longer exists. Delete moves the highlight to the row that took the slot, which is what ActiveListSelection.Slide does. --- .../client/settings/agents/WorkflowsConfigurable.kt | 2 +- .../client/settings/agents/WorkflowsSettingsUiTest.kt | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/WorkflowsConfigurable.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/WorkflowsConfigurable.kt index 2c0eee431723..38ca2fa250e9 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/WorkflowsConfigurable.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/settings/agents/WorkflowsConfigurable.kt @@ -245,7 +245,7 @@ internal class WorkflowsSettingsUi( ) if (result != Messages.YES) return state.update { copy(deleted = deleted + flow.location, edited = edited - flow.location) } - view.update(rows(), selectionIndex()) + view.update(rows(), ActiveListSelection.Slide) } private fun content(flow: CommandFileDto) = draft.edited[flow.location] ?: flow.content diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/WorkflowsSettingsUiTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/WorkflowsSettingsUiTest.kt index 5696e261d897..51c52516febd 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/WorkflowsSettingsUiTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/agents/WorkflowsSettingsUiTest.kt @@ -212,6 +212,17 @@ class WorkflowsSettingsUiTest : BasePlatformTestCase() { assertEquals(listOf(DIR to CUSTOM), agentRpc.commandRemovals) } + fun `test delete selects the workflow that took the deleted slot`() { + val panel = panel() + flushUntil { rows(panel).size == 3 } + val next = edt { rows(panel)[1].key } + TestDialogManager.setTestDialog(TestDialog.YES) + + click(workflowsList(panel), panel, CUSTOM, "delete") + + assertEquals(next, edt { workflowsList(panel).selectedValue?.key }) + } + fun `test delete action requires confirmation`() { val panel = panel() flushUntil { rows(panel).size == 3 } From 34a7eb34a1b9ea945a613ef0df1685676dc479a6 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 16:05:49 -0400 Subject: [PATCH 16/30] fix(jetbrains): align session and worktree icons Use the Kilo running spinner anywhere the session UI showed the default platform spinner, so progress indicators match the Agent Manager running state. Restore branch and lock glyphs as the resting Agent Manager worktree icons, add a JetBrains-styled local monitor icon for the current checkout, and remove the now-unused idle dot icon. --- .changeset/jetbrains-session-spinner.md | 5 ++ .changeset/jetbrains-worktree-row-icons.md | 5 ++ .../client/agentManager/AgentManagerPanel.kt | 2 +- .../agentManager/worktree/WorktreeIcons.kt | 49 +++++++++++-------- .../ai/kilocode/client/session/IdleIcon.kt | 36 -------------- .../client/session/ui/ProgressPanel.kt | 4 +- .../client/session/ui/RevertProgress.kt | 4 +- .../ui/attachment/AttachmentEditorKind.kt | 4 +- .../client/session/ui/prompt/PromptPanel.kt | 4 +- .../main/resources/icons/worktree-local.svg | 4 ++ .../resources/icons/worktree-local_dark.svg | 4 ++ .../agentManager/AgentManagerPanelTest.kt | 27 +++++++++- .../agentManager/WorktreeControllerTest.kt | 7 ++- .../client/agentManager/WorktreeIconsTest.kt | 31 ++++++++---- .../client/session/ui/ProgressPanelTest.kt | 2 + .../client/session/ui/PromptPanelTest.kt | 2 + .../client/session/ui/RevertProgressTest.kt | 18 +++++++ 17 files changed, 130 insertions(+), 78 deletions(-) create mode 100644 .changeset/jetbrains-session-spinner.md create mode 100644 .changeset/jetbrains-worktree-row-icons.md delete mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/IdleIcon.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg create mode 100644 packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local_dark.svg diff --git a/.changeset/jetbrains-session-spinner.md b/.changeset/jetbrains-session-spinner.md new file mode 100644 index 000000000000..ce8d9a6fbdd5 --- /dev/null +++ b/.changeset/jetbrains-session-spinner.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Use the Kilo running spinner across session progress indicators. diff --git a/.changeset/jetbrains-worktree-row-icons.md b/.changeset/jetbrains-worktree-row-icons.md new file mode 100644 index 000000000000..33c484104a7f --- /dev/null +++ b/.changeset/jetbrains-worktree-row-icons.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Show branch icons on Agent Manager worktree rows again, and mark the current checkout with a local machine icon. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 464cb7cc6a42..00a8620003ae 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -480,7 +480,7 @@ class AgentManagerPanel( override val title: String get() = if (current) dto.branch else WorktreeTitle.text(dto.name, dto.path, pr) override val description: String get() = WorktreeTitle.fallback(dto.path) override val tooltip: String? get() = null - override val icon = WorktreeIcons.forRow(pending, kind) + override val icon = WorktreeIcons.forRow(pending, kind, dto.locked, current) override val section: String? get() = if (current) null else KiloBundle.message("worktree.section.local") override val search: String get() = listOfNotNull(dto.name, dto.branch, dto.path, dto.lockReason).joinToString(" ") private val customName: String? get() = WorktreeTitle.custom(dto.name, dto.path) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt index 36e81fa935dc..9f9d789c4f58 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt @@ -1,6 +1,5 @@ package ai.kilocode.client.agentManager.worktree -import ai.kilocode.client.session.IdleIcon import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.client.session.SpinnerIcon import com.intellij.openapi.util.IconLoader @@ -10,30 +9,40 @@ import javax.swing.Icon internal object WorktreeIcons { val branch: Icon = IconLoader.getIcon("/icons/worktreeBranch.svg", WorktreeIcons::class.java) val locked: Icon = IconLoader.getIcon("/icons/worktreeLock.svg", WorktreeIcons::class.java) + + // The current checkout is the machine you work on rather than a branch checkout, so it gets the + // monitor glyph the VS Code agent manager uses for the same row. + val local: Icon = IconLoader.getIcon("/icons/worktree-local.svg", WorktreeIcons::class.java) val spinner: Icon = AnimatedIcon.Default.INSTANCE // Single swap point for the running-session icon. Change this to retarget the animation // (e.g. AnimatedIcon.Default.INSTANCE or SessionActivityKind.RUNNING.icon()). val running: Icon = SpinnerIcon.icon - // Small muted dot the size of the status icons. An idle row keeps the same leading slot so the - // title never shifts, but the dot reads as quieter and smaller than the running/question glyphs. - val idle: Icon = IdleIcon - - // A worktree row shows the running spinner or the "?" attention glyph while a session there is - // active; idle, locked, and errored rows fall back to the small [idle] dot. [pending] (creation - // in progress) still shows the platform spinner. - fun forRow(pending: Boolean, kind: SessionActivityKind? = null): Icon = - if (pending) spinner else forKind(kind) - - // Status icon for a single session: the spinner while running, the "?" attention glyph while - // waiting for input, and the small [idle] dot otherwise. - fun forKind(kind: SessionActivityKind?): Icon = when (kind) { - SessionActivityKind.RUNNING -> running - SessionActivityKind.QUESTION, - SessionActivityKind.PERMISSION, - SessionActivityKind.PLAN, - SessionActivityKind.LOGIN_REQUIRED -> kind.icon() - SessionActivityKind.ERROR, null -> idle + /** + * Leading icon for a worktree row. At rest the row shows what it is — the local machine, a locked + * checkout, or a branch checkout — while a running or waiting session takes the slot over so the + * list still surfaces activity at a glance. Creation ([pending]) outranks all of it, and an + * errored session falls back to the resting glyph instead of shouting in the leading slot. + */ + fun forRow( + pending: Boolean, + kind: SessionActivityKind? = null, + locked: Boolean = false, + current: Boolean = false, + ): Icon { + if (pending) return spinner + return when (kind) { + SessionActivityKind.RUNNING -> running + SessionActivityKind.QUESTION, + SessionActivityKind.PERMISSION, + SessionActivityKind.PLAN, + SessionActivityKind.LOGIN_REQUIRED -> kind.icon() + SessionActivityKind.ERROR, null -> when { + current -> local + locked -> this.locked + else -> branch + } + } } } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/IdleIcon.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/IdleIcon.kt deleted file mode 100644 index 43ae74c2e5a6..000000000000 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/IdleIcon.kt +++ /dev/null @@ -1,36 +0,0 @@ -package ai.kilocode.client.session - -import com.intellij.util.ui.JBUI -import com.intellij.util.ui.NamedColorUtil -import java.awt.Component -import java.awt.Graphics -import java.awt.Graphics2D -import java.awt.RenderingHints -import java.awt.geom.Ellipse2D -import javax.swing.Icon - -/** - * Idle-status glyph: a small muted dot centered in the same 16x16 bounds the running and - * question icons use. Keeping the bounds identical stops the row title from shifting when a - * session goes active or idle, while the deliberately smaller dot reads as quieter than the - * larger running/question glyphs that fill the icon. - */ -internal object IdleIcon : Icon { - override fun getIconWidth() = JBUI.scale(16) - - override fun getIconHeight() = JBUI.scale(16) - - override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) { - val g2 = g.create() as Graphics2D - try { - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - g2.translate(x, y) - g2.color = NamedColorUtil.getInactiveTextColor() - val dot = JBUI.scale(6).toFloat() - val origin = (iconWidth - dot) / 2f - g2.fill(Ellipse2D.Float(origin, origin, dot, dot)) - } finally { - g2.dispose() - } - } -} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/ProgressPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/ProgressPanel.kt index 4a461abef582..9b8fb9cc8cdb 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/ProgressPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/ProgressPanel.kt @@ -1,6 +1,7 @@ package ai.kilocode.client.session.ui import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.session.SpinnerIcon import ai.kilocode.client.session.model.SessionModel import ai.kilocode.client.session.model.SessionModelEvent import ai.kilocode.client.session.model.SessionState @@ -14,7 +15,6 @@ import ai.kilocode.client.util.UiTimerSource import ai.kilocode.client.util.UiTimers import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer -import com.intellij.ui.AnimatedIcon import com.intellij.ui.components.JBLabel import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel @@ -48,7 +48,7 @@ class ProgressPanel( private val elapsed = JBLabel().apply { foreground = SessionUiStyle.Text.Secondary.foreground() } - private val spinner = JBLabel(AnimatedIcon.Default()) + private val spinner = JBLabel(SpinnerIcon.icon) private val tick = clock.timer(1000) { syncElapsed() } init { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/RevertProgress.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/RevertProgress.kt index 99a09023a0fa..0d0c871c6017 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/RevertProgress.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/RevertProgress.kt @@ -1,12 +1,12 @@ package ai.kilocode.client.session.ui import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.session.SpinnerIcon import ai.kilocode.client.session.ui.style.SessionEditorStyle import ai.kilocode.client.session.ui.style.SessionEditorStyleTarget import ai.kilocode.client.session.ui.style.SessionUiStyle import ai.kilocode.client.ui.UiStyle import ai.kilocode.client.ui.layout.Stack -import com.intellij.ui.AnimatedIcon import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBLabel import com.intellij.util.concurrency.annotations.RequiresEdt @@ -20,7 +20,7 @@ class RevertProgress(onCancel: () -> Unit) : JPanel(), SessionEditorStyleTarget init { isOpaque = false add(Stack.horizontal(UiStyle.Gap.sm()) - .next(JBLabel(AnimatedIcon.Default())) + .next(JBLabel(SpinnerIcon.icon)) .next(label) .next(cancel)) applyStyle(style) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/attachment/AttachmentEditorKind.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/attachment/AttachmentEditorKind.kt index a10409fc32a3..937d974809c3 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/attachment/AttachmentEditorKind.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/attachment/AttachmentEditorKind.kt @@ -4,6 +4,7 @@ import ai.kilocode.client.app.KiloAppService import ai.kilocode.client.app.KiloSessionService import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.session.model.FileAttachment +import ai.kilocode.client.session.SpinnerIcon import ai.kilocode.client.ui.UiStyle import ai.kilocode.client.ui.layout.Stack import ai.kilocode.client.vfs.KiloEditorKind @@ -16,7 +17,6 @@ import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer -import com.intellij.ui.AnimatedIcon import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBScrollPane @@ -111,7 +111,7 @@ private fun component(data: AttachmentData): JComponent = when (data) { private fun connecting(): JComponent { return Stack.horizontal(gap = UiStyle.Gap.sm()).apply { border = JBUI.Borders.empty(UiStyle.Gap.pad()) - next(JBLabel(AnimatedIcon.Default())) + next(JBLabel(SpinnerIcon.icon)) next(JBLabel(KiloBundle.message("session.connection.connecting"))) }.let { Centerizer(it, Centerizer.TYPE.BOTH) } } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/prompt/PromptPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/prompt/PromptPanel.kt index 055f85af82e8..5a47d7ebd9a2 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/prompt/PromptPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/prompt/PromptPanel.kt @@ -4,6 +4,7 @@ import ai.kilocode.client.KiloNotifications import ai.kilocode.client.actions.SendPromptAction import ai.kilocode.client.actions.StopSessionAction import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.session.SpinnerIcon import ai.kilocode.client.session.ui.ReasoningPicker import ai.kilocode.client.session.ui.SessionRootPanel import ai.kilocode.client.session.model.PromptAttachment @@ -61,7 +62,6 @@ import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader -import com.intellij.ui.AnimatedIcon import com.intellij.ui.IslandsState import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.xml.util.XmlStringUtil @@ -247,7 +247,7 @@ class PromptPanel( addActionListener { onAutoApproveToggle(!autoApprove) } } - private val enhancingIcon = AnimatedIcon.Default() + private val enhancingIcon = SpinnerIcon.icon private val enhance = HoverIcon().apply { icon = WAND_ICON toolTipText = KiloBundle.message("prompt.action.enhance") diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg new file mode 100644 index 000000000000..5b8ac7a3c348 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg @@ -0,0 +1,4 @@ + + + + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local_dark.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local_dark.svg new file mode 100644 index 000000000000..e3ce494b8b60 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index b9c2c4182d28..64580e720b53 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -492,7 +492,7 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(emptyList(), row.badges) } - fun `test worktree row uses the idle dot for error activity`() { + fun `test worktree row uses the branch icon for error activity`() { val item = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") val activity = MutableStateFlow(mapOf( "ses_1" to SessionActivityDto(item.path, SessionActivityKindDto.ERROR), @@ -503,7 +503,30 @@ class AgentManagerPanelTest : BasePlatformTestCase() { edt { controller.reload() } flush() - assertSame(WorktreeIcons.idle, row(panel, 0).icon) + assertSame(WorktreeIcons.branch, row(panel, 0).icon) + } + + fun `test idle worktree rows show the branch icon and the local row shows the monitor`() { + rpc.listed += main() + rpc.listed += worktree("aardvark") + val controller = WorktreeController(service, project.basePath!!, coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + + assertSame(WorktreeIcons.local, row(panel, 0).icon) + assertSame(WorktreeIcons.branch, row(panel, 1).icon) + } + + fun `test locked worktree row shows the lock icon`() { + val path = "${project.basePath!!}/.kilo/worktrees/held" + rpc.listed += WorktreeDto(path, "held", "held", path, locked = true, lockReason = "held by test") + val controller = WorktreeController(service, project.basePath!!, coroutines.scope) + val panel = edt { AgentManagerPanel(testRootDisposable, controller, project) } + edt { controller.reload() } + flush() + + assertSame(WorktreeIcons.locked, row(panel, 0).icon) } fun `test worktree row shows metrics from status service`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt index 9de9cc52dad2..dffd2030e5ff 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt @@ -368,8 +368,8 @@ class WorktreeControllerTest : BasePlatformTestCase() { SessionActivityKind.PLAN.icon(), WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.PLAN), ) - assertSame(WorktreeIcons.idle, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR)) - assertSame(WorktreeIcons.idle, WorktreeIcons.forRow(pending = false, kind = null)) + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR)) + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(pending = false, kind = null)) } fun `test worktree icons load at the same size`() { @@ -379,8 +379,11 @@ class WorktreeControllerTest : BasePlatformTestCase() { try { assertTrue("branch icon should load", WorktreeIcons.branch.iconWidth > 1) assertTrue("lock icon should load", WorktreeIcons.locked.iconWidth > 1) + assertTrue("local icon should load", WorktreeIcons.local.iconWidth > 1) assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.locked.iconWidth) assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.locked.iconHeight) + assertEquals(WorktreeIcons.branch.iconWidth, WorktreeIcons.local.iconWidth) + assertEquals(WorktreeIcons.branch.iconHeight, WorktreeIcons.local.iconHeight) for (kind in SessionActivityKind.entries) { assertEquals(WorktreeIcons.branch.iconWidth, kind.icon().iconWidth) assertEquals(WorktreeIcons.branch.iconHeight, kind.icon().iconHeight) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt index e272137d6253..0487124a8052 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt @@ -22,18 +22,31 @@ class WorktreeIconsTest : BasePlatformTestCase() { } fun `test waiting kinds resolve to the attention glyph`() { - assertSame(SessionActivityKind.QUESTION.icon(), WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.QUESTION)) - assertSame(SessionActivityKind.PLAN.icon(), WorktreeIcons.forKind(SessionActivityKind.PLAN)) + assertSame( + SessionActivityKind.QUESTION.icon(), + WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.QUESTION), + ) + assertSame(SessionActivityKind.PLAN.icon(), WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.PLAN)) } - fun `test idle and errored rows use the idle dot`() { - assertSame(WorktreeIcons.idle, WorktreeIcons.forRow(pending = false, kind = null)) - assertSame(WorktreeIcons.idle, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR)) - assertSame(WorktreeIcons.idle, WorktreeIcons.forKind(null)) + fun `test rows at rest show what the checkout is`() { + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(pending = false)) + assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(pending = false, locked = true)) + assertSame(WorktreeIcons.local, WorktreeIcons.forRow(pending = false, current = true)) } - fun `test idle dot matches the status icon size`() { - assertEquals(WorktreeIcons.running.iconWidth, WorktreeIcons.idle.iconWidth) - assertEquals(WorktreeIcons.running.iconHeight, WorktreeIcons.idle.iconHeight) + fun `test errored session falls back to the resting glyph`() { + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR)) + assertSame( + WorktreeIcons.local, + WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR, current = true), + ) + } + + fun `test activity outranks the resting glyph on the local row`() { + assertSame( + WorktreeIcons.running, + WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.RUNNING, current = true), + ) } } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/ProgressPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/ProgressPanelTest.kt index 452f1bae0150..d23454c5ee60 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/ProgressPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/ProgressPanelTest.kt @@ -1,6 +1,7 @@ package ai.kilocode.client.session.ui import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.session.SpinnerIcon import ai.kilocode.client.session.model.Permission import ai.kilocode.client.session.model.PermissionMeta import ai.kilocode.client.session.model.SessionModel @@ -55,6 +56,7 @@ class ProgressPanelTest : BasePlatformTestCase() { model.setState(SessionState.Busy("Thinking\u2026")) assertTrue(panel.isVisible) + assertSame(SpinnerIcon.icon, spinner().icon) assertEquals("Thinking\u2026", panel.labelText()) assertEquals("0s", panel.elapsedText()) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/PromptPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/PromptPanelTest.kt index d929f46ac053..6c161c4da82c 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/PromptPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/PromptPanelTest.kt @@ -1,5 +1,6 @@ package ai.kilocode.client.session.ui +import ai.kilocode.client.session.SpinnerIcon import ai.kilocode.client.session.ui.style.SessionEditorStyle import ai.kilocode.client.app.KiloWorkspaceService import ai.kilocode.client.plugin.KiloBundle @@ -1341,6 +1342,7 @@ class PromptPanelTest : BasePlatformTestCase() { assertEquals("make a plan", seen) assertFalse(enhance.isEnabled) assertTrue(enhance.icon is AnimatedIcon) + assertSame(SpinnerIcon.icon, enhance.icon) val icon = enhance.icon panel.setReady(true) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/RevertProgressTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/RevertProgressTest.kt index ffbd2db21f46..792f8e595abe 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/RevertProgressTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/RevertProgressTest.kt @@ -1,5 +1,6 @@ package ai.kilocode.client.session.ui +import ai.kilocode.client.session.SpinnerIcon import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBLabel @@ -20,6 +21,12 @@ class RevertProgressTest : BasePlatformTestCase() { assertSame(label, label(view)) } + fun `test uses session spinner`() { + val view = RevertProgress {} + + assertSame(SpinnerIcon.icon, spinner(view).icon) + } + fun `test cancel invokes callback`() { var done = false val view = RevertProgress { done = true } @@ -50,4 +57,15 @@ class RevertProgressTest : BasePlatformTestCase() { } error("missing cancel") } + + private fun spinner(root: Container): JBLabel { + for (child in root.components) { + if (child is JBLabel && child.icon != null) return child + if (child is Container) { + val found = runCatching { spinner(child) }.getOrNull() + if (found != null) return found + } + } + error("missing spinner") + } } From 0879741e992a8de6ea53241a2e0ea03d8b05405f Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 16:14:13 -0400 Subject: [PATCH 17/30] fix(jetbrains): move PR number after the worktree title Keep the PR state badge first, but render the pull request number after the PR title so the header reads like the worktree list and avoids leading with metadata. --- .../client/agentManager/worktree/WorktreePrHeaderView.kt | 8 ++++---- .../agentManager/worktree/WorktreePrHeaderViewTest.kt | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt index 90a2ea0f2eaf..79fc3650bcba 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt @@ -132,17 +132,17 @@ internal class WorktreePrHeaderView( changed() } - private fun syncTitle(prefix: String, next: String?, nextTip: String?) { - val full = listOfNotNull(prefix, next).joinToString(" ") + private fun syncTitle(number: String, next: String?, nextTip: String?) { + val full = listOfNotNull(next, number).joinToString(" ") var changed = false if (text != full) { text = full title.clear() if (next == null) { - title.append(prefix, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) + title.append(number, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) } else { - title.append("$prefix ", SimpleTextAttributes.GRAYED_ATTRIBUTES) title.append(next, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) + title.append(" $number", SimpleTextAttributes.GRAYED_ATTRIBUTES) } changed = true } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt index e738c1fa7fb2..96e0f2572caf 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt @@ -34,9 +34,9 @@ class WorktreePrHeaderViewTest : BasePlatformTestCase() { assertEquals(stateLabel(GhState.OPEN), (badge.icon as FilledBadgeIcon).text) assertSame(style(GhState.OPEN), (badge.icon as FilledBadgeIcon).style) assertTrue(badge.isVisible) - assertEquals(listOf("#123 ", "Implement header"), fragments.map { it.text }) - assertEquals(SimpleTextAttributes.GRAYED_ATTRIBUTES.fgColor, fragments[0].attrs.fgColor) - assertEquals(SimpleTextAttributes.STYLE_BOLD, fragments[1].attrs.style) + assertEquals(listOf("Implement header", " #123"), fragments.map { it.text }) + assertEquals(SimpleTextAttributes.STYLE_BOLD, fragments[0].attrs.style) + assertEquals(SimpleTextAttributes.GRAYED_ATTRIBUTES.fgColor, fragments[1].attrs.fgColor) assertEquals(Cursor.HAND_CURSOR, title.cursor.type) assertEquals(Cursor.HAND_CURSOR, badge.cursor.type) assertTrue(title.toolTipText.contains("Open #123 Implement header")) From 64c14abc77d0b674366f0fbcfe4b61c3e19b83a3 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 16:52:03 -0400 Subject: [PATCH 18/30] fix(jetbrains): use regular title weight in active lists ActiveList titles were rendered bold for every row, which made Agent Manager, history, and settings lists read heavier than standard IDE lists and trees. Use the platform plain text style for the primary row title while keeping the explicit foreground so selected and deleting rows retain their color behavior. --- .changeset/jetbrains-list-title-weight.md | 5 +++++ .../client/ui/list/ActiveListRenderer.kt | 5 ++++- .../settings/base/SettingsListViewTest.kt | 19 +++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 .changeset/jetbrains-list-title-weight.md diff --git a/.changeset/jetbrains-list-title-weight.md b/.changeset/jetbrains-list-title-weight.md new file mode 100644 index 000000000000..01b31c502ccd --- /dev/null +++ b/.changeset/jetbrains-list-title-weight.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Render list row titles in the regular weight so Agent Manager, history, and settings lists match the rest of the IDE. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt index 10511db6e618..4d3c8e8f8ec0 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt @@ -221,7 +221,10 @@ internal class ActiveListRenderer( layers.isVisible = true title.clear() - title.append(value.title, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, titleFg)) + // Plain, like every platform list and tree renders its primary text. Bold reads as emphasis in + // the IDE (the current branch, an unread entry), so bolding every row makes the list look + // heavier than the surfaces around it. + title.append(value.title, SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, titleFg)) value.note?.takeIf { it.isNotBlank() }?.let { title.append(" $it", SimpleTextAttributes.GRAYED_ATTRIBUTES) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt index c7101e0611de..ebcf191fc513 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt @@ -32,6 +32,7 @@ import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.ui.CollectionListModel import com.intellij.ui.ScrollingUtil import com.intellij.ui.SimpleColoredComponent +import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBList import com.intellij.ui.components.JBScrollPane @@ -198,6 +199,24 @@ class SettingsListViewTest : BasePlatformTestCase() { } } + fun `test renderer draws the row title in the plain list weight`() { + edt { + val row = item("with", "Alpha", "Description") + val model = CollectionListModel(listOf(row)) + val list = JBList(model) + val renderer = ActiveListRenderer(model, ActiveListConfig.Equal) + + renderer.getListCellRendererComponent(list, row, 0, true, true) + + // Bold reads as emphasis in platform lists, so rows must stay plain like tree/list text. + val title = components(renderer).filterIsInstance().single() + val iter = title.iterator() + iter.next() + assertEquals(SimpleTextAttributes.STYLE_PLAIN, iter.textAttributes.style) + assertEquals("Alpha", iter.fragment) + } + } + fun `test narrow row squeezes title but keeps tags full width`() { edt { val row = object : ActiveListItem { From 31b7297dd05264e4b665ad3d2248e11ecc9a8ae1 Mon Sep 17 00:00:00 2001 From: kirillk Date: Fri, 21 Aug 2026 17:32:30 -0400 Subject: [PATCH 19/30] fix(jetbrains): mute worktree metadata styling Keep ActiveList titles bold, but keep descriptions muted even under selection so the secondary line does not collapse into the title foreground. Recolor the resting worktree glyphs to the New UI secondary icon palette, which matches Label.infoForeground/context help text, and paint the running spinner in neutral icon grey instead of green so it stays bright without becoming a colored status light. --- ...etbrains-list-description-spinner-color.md | 5 +++ .changeset/jetbrains-list-title-weight.md | 5 --- .../ai/kilocode/client/session/SpinnerIcon.kt | 7 +++- .../kotlin/ai/kilocode/client/ui/UiStyle.kt | 11 +++++ .../client/ui/list/ActiveListRenderer.kt | 9 ++-- .../main/resources/icons/worktree-local.svg | 4 +- .../resources/icons/worktree-local_dark.svg | 4 +- .../main/resources/icons/worktreeBranch.svg | 2 +- .../resources/icons/worktreeBranch_dark.svg | 2 +- .../src/main/resources/icons/worktreeLock.svg | 2 +- .../resources/icons/worktreeLock_dark.svg | 2 +- .../client/agentManager/WorktreeIconsTest.kt | 41 +++++++++++++++++++ .../settings/base/SettingsListViewTest.kt | 22 ++++++++-- 13 files changed, 92 insertions(+), 24 deletions(-) create mode 100644 .changeset/jetbrains-list-description-spinner-color.md delete mode 100644 .changeset/jetbrains-list-title-weight.md diff --git a/.changeset/jetbrains-list-description-spinner-color.md b/.changeset/jetbrains-list-description-spinner-color.md new file mode 100644 index 000000000000..53229be14e08 --- /dev/null +++ b/.changeset/jetbrains-list-description-spinner-color.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Keep list descriptions muted while their row is selected, mute the worktree row icons to match the description text, and paint the running spinner in the neutral icon grey so it stays legible in light and dark themes. diff --git a/.changeset/jetbrains-list-title-weight.md b/.changeset/jetbrains-list-title-weight.md deleted file mode 100644 index 01b31c502ccd..000000000000 --- a/.changeset/jetbrains-list-title-weight.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"@kilocode/kilo-jetbrains": patch ---- - -Render list row titles in the regular weight so Agent Manager, history, and settings lists match the rest of the IDE. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt index 66d5c5021502..ffb5d0e0de83 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt @@ -15,7 +15,8 @@ import kotlin.math.cos /** * Animated running badge that mirrors the VS Code Agent Manager spinner: a 4x4 grid of rounded * squares whose opacity pulses. Corners stay empty; the inner squares pulse brighter than the - * outer ring. Rendered in the amber "running" brand color ([UiStyle.Badge.ActivityRunning]). + * outer ring. Painted in the neutral icon grey ([UiStyle.Colors.running]) so it carries the same + * weight as the static row icons it stands in for. * * Built as a frame-based [com.intellij.ui.AnimatedIcon] so it animates automatically inside list * cell renderers that set `AnimatedIcon.ANIMATION_IN_RENDERER_ALLOWED` (see `ActiveListView`). @@ -77,7 +78,7 @@ internal object SpinnerIcon { val scale = iconWidth / VIEWBOX val size = SQUARE * scale val arc = RADIUS * 2f * scale - val base = UiStyle.Badge.ActivityRunning.fg() + val base = color() for (i in 0 until COUNT) { if (i in CORNERS) continue g2.color = ColorUtil.withAlpha(base, opacity(i, frame).toDouble()) @@ -90,4 +91,6 @@ internal object SpinnerIcon { } } } + + fun color() = UiStyle.Colors.running() } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt index 2e2c9d687f7d..cc87182d10f5 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt @@ -200,6 +200,17 @@ object UiStyle { fun weak(): Color = UIUtil.getContextHelpForeground() + // Neutral icon greys from the New UI palette: the same values our svg row icons paint with, so + // an animated icon reads at the row's icon weight instead of as a colored status light. Each + // variant carries the contrast its own theme needs — mid grey on light, near-white on dark. + val runningLight = Color(0x6C, 0x70, 0x7E) + val runningDark = Color(0xCE, 0xD0, 0xD6) + + fun running(): Color = JBColor.namedColor( + "Kilo.Activity.runningSpinnerForeground", + JBColor(runningLight, runningDark), + ) + /** Uses the editor background so chat cards feel native beside editor content. */ fun editorBackground(): Color = JBColor.lazy { EditorColorsManager.getInstance().globalScheme.defaultBackground } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt index 4d3c8e8f8ec0..276767e2dcd0 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt @@ -191,7 +191,7 @@ internal class ActiveListRenderer( ): JPanel { val active = selected && (focused || list.hasFocus() || (list as? ActiveListActive)?.active() == true) val fg = UIUtil.getListForeground(active, active || focused) - val weak = if (active) fg else UiStyle.Colors.weak() + val weak = UiStyle.Colors.weak() val titleFg = if (value.deleting) weak else fg val section = activeListSectionTitle(model.items, index) @@ -221,10 +221,9 @@ internal class ActiveListRenderer( layers.isVisible = true title.clear() - // Plain, like every platform list and tree renders its primary text. Bold reads as emphasis in - // the IDE (the current branch, an unread entry), so bolding every row makes the list look - // heavier than the surfaces around it. - title.append(value.title, SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, titleFg)) + // Bold carries the row: the description under it and the icon beside it both render in the + // muted secondary color, so weight is what separates the two lines rather than color alone. + title.append(value.title, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, titleFg)) value.note?.takeIf { it.isNotBlank() }?.let { title.append(" $it", SimpleTextAttributes.GRAYED_ATTRIBUTES) } diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg index 5b8ac7a3c348..c5481bc9297a 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg @@ -1,4 +1,4 @@ - - + + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local_dark.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local_dark.svg index e3ce494b8b60..d40fa8f60f49 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local_dark.svg +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local_dark.svg @@ -1,4 +1,4 @@ - - + + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeBranch.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeBranch.svg index 46fa01509602..58184b7a91bd 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeBranch.svg +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeBranch.svg @@ -1 +1 @@ - + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeBranch_dark.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeBranch_dark.svg index 0e8f92d4cd37..003576128204 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeBranch_dark.svg +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeBranch_dark.svg @@ -1 +1 @@ - + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeLock.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeLock.svg index 37de9293762f..bf088c0803d1 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeLock.svg +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeLock.svg @@ -1 +1 @@ - + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeLock_dark.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeLock_dark.svg index d43729b67557..d679769eb602 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeLock_dark.svg +++ b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktreeLock_dark.svg @@ -1 +1 @@ - + diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt index 0487124a8052..e0e04c05b06c 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt @@ -2,9 +2,13 @@ package ai.kilocode.client.agentManager import ai.kilocode.client.agentManager.worktree.WorktreeIcons import ai.kilocode.client.session.SessionActivityKind +import ai.kilocode.client.session.SpinnerIcon +import ai.kilocode.client.ui.UiStyle import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.ui.AnimatedIcon +import com.intellij.ui.ColorUtil import com.intellij.util.ui.JBUI +import java.awt.Color class WorktreeIconsTest : BasePlatformTestCase() { fun `test running session resolves to the animated spinner`() { @@ -17,6 +21,43 @@ class WorktreeIconsTest : BasePlatformTestCase() { assertEquals(JBUI.scale(16), WorktreeIcons.running.iconHeight) } + fun `test resting row icons carry the muted palette in both themes`() { + for (name in listOf("worktreeBranch", "worktreeLock", "worktree-local")) { + // The secondary New UI greys, which are also what Label.infoForeground resolves to, so a + // resting glyph sits at the weight of the description line under it rather than the title. + val light = svg(name).replace("#818594", "GLYPH") + val dark = svg("${name}_dark").replace("#6F737A", "GLYPH") + + assertFalse("$name still uses a primary grey", light.contains("#6C707E")) + assertFalse("${name}_dark still uses a primary grey", dark.contains("#CED0D6")) + // Recoloring must be the only difference: the loader animates between the two. + assertEquals("$name geometry drifted from its dark variant", light, dark) + } + } + + private fun svg(name: String): String { + val stream = WorktreeIcons::class.java.getResourceAsStream("/icons/$name.svg") + return checkNotNull(stream) { "missing /icons/$name.svg" }.use { it.readBytes().decodeToString() } + } + + fun `test running spinner paints a neutral grey that carries contrast in both themes`() { + assertEquals(UiStyle.Colors.running().rgb, SpinnerIcon.color().rgb) + + // Neutral: no channel pulls the grey towards a hue. + assertTrue("light variant is not neutral", spread(UiStyle.Colors.runningLight) <= 24) + assertTrue("dark variant is not neutral", spread(UiStyle.Colors.runningDark) <= 24) + + // Each variant stands out against the background its own theme paints behind the row. + assertTrue("light variant is too pale", ColorUtil.isDark(UiStyle.Colors.runningLight)) + assertFalse("dark variant is too dim", ColorUtil.isDark(UiStyle.Colors.runningDark)) + } + + /** Distance between the strongest and weakest channel, i.e. how far the color is from pure grey. */ + private fun spread(color: Color): Int { + val channels = listOf(color.red, color.green, color.blue) + return channels.max() - channels.min() + } + fun `test pending outranks running and uses the platform spinner`() { assertSame(WorktreeIcons.spinner, WorktreeIcons.forRow(pending = true, kind = SessionActivityKind.RUNNING)) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt index ebcf191fc513..2837e0e58d02 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/settings/base/SettingsListViewTest.kt @@ -199,7 +199,7 @@ class SettingsListViewTest : BasePlatformTestCase() { } } - fun `test renderer draws the row title in the plain list weight`() { + fun `test renderer draws the row title in bold`() { edt { val row = item("with", "Alpha", "Description") val model = CollectionListModel(listOf(row)) @@ -208,11 +208,11 @@ class SettingsListViewTest : BasePlatformTestCase() { renderer.getListCellRendererComponent(list, row, 0, true, true) - // Bold reads as emphasis in platform lists, so rows must stay plain like tree/list text. + // Weight is what separates the title from the muted description beside and below it. val title = components(renderer).filterIsInstance().single() val iter = title.iterator() iter.next() - assertEquals(SimpleTextAttributes.STYLE_PLAIN, iter.textAttributes.style) + assertEquals(SimpleTextAttributes.STYLE_BOLD, iter.textAttributes.style) assertEquals("Alpha", iter.fragment) } } @@ -464,6 +464,20 @@ class SettingsListViewTest : BasePlatformTestCase() { } } + fun `test focused selected row keeps description muted`() { + edt { + val row = item("with", "Alpha", "Description") + val model = CollectionListModel(listOf(row)) + val list = JBList(model) + val renderer = ActiveListRenderer(model, ActiveListConfig.Equal) + + renderer.getListCellRendererComponent(list, row, 0, true, true) + + val desc = components(renderer).filterIsInstance().single { it.text == "Description" } + assertEquals(UiStyle.Colors.weak(), desc.foreground) + } + } + fun `test unfocused selected row paints inactive selection background`() { edt { val row = item("with", "Alpha", "Description") @@ -763,7 +777,7 @@ class SettingsListViewTest : BasePlatformTestCase() { renderer.getListCellRendererComponent(list, row, 0, true, false) val desc = components(renderer).filterIsInstance().single { it.text == "Description" } - assertEquals(UIUtil.getListForeground(true, true), desc.foreground) + assertEquals(UiStyle.Colors.weak(), desc.foreground) } } From 76faa3004b77624d6181e2cad511138e77f364e1 Mon Sep 17 00:00:00 2001 From: kirillk Date: Sun, 23 Aug 2026 18:18:58 -0400 Subject: [PATCH 20/30] feat(jetbrains): add chat branch/PR dock with worktree actions Add a branch/PR dock above the chat prompt in the JetBrains sidebar. It shows the current branch's PR (state badge + title + changes) when one exists, and otherwise a centered row of New Worktree / Move to Worktree actions plus a changes badge, matching the VS Code sidebar dock. New Worktree and Move to Worktree are registered platform actions (Kilo.Chat.NewWorktree, Kilo.Chat.MoveToWorktree) rendered through an ActionToolbar; each is invisible when not enabled, so the dock collapses when there is nothing to show. New Worktree opens the Agent Manager New Worktree dialog and switches to that tab after the dialog closes. Move to Worktree captures uncommitted changes, creates a worktree at the source HEAD, transfers the changes, and forks the session into it, streaming progress into the dock. Branch/PR status uses the session's resolved directory (not the synthetic split-mode project path) so the PR always matches the checked-out branch. --- .../backend/app/KiloBackendSessionManager.kt | 35 ++++ .../backend/rpc/KiloWorktreeRpcApiImpl.kt | 75 +++++++ .../kilocode/backend/rpc/WorktreeTransfer.kt | 157 ++++++++++++++ .../app/KiloBackendSessionManagerTest.kt | 51 +++++ .../backend/rpc/KiloWorktreeRpcApiImplTest.kt | 73 +++++++ .../kilocode/backend/testing/MockCliServer.kt | 9 + .../kilocode/client/KiloToolWindowFactory.kt | 8 + .../actions/ChatMoveToWorktreeAction.kt | 64 ++++++ .../client/actions/ChatNewWorktreeAction.kt | 31 +++ .../client/agentManager/AgentManagerPanel.kt | 7 +- .../worktree/KiloWorktreeService.kt | 17 ++ .../agentManager/worktree/MoveToWorktree.kt | 72 +++++++ .../worktree/WorktreePrHeaderView.kt | 143 +------------ .../worktree/WorktreeSessionEditorKind.kt | 8 +- .../worktree/WorktreeSessionEditorManager.kt | 8 +- .../worktree/WorktreeStatsView.kt | 37 +--- .../kilocode/client/session/SessionManager.kt | 8 +- .../client/session/SessionSidePanelManager.kt | 9 + .../ai/kilocode/client/session/SessionUi.kt | 119 ++++++++--- .../subagent/SubagentSessionEditorHost.kt | 2 +- .../client/session/ui/header/BranchDock.kt | 183 ++++++++++++++++ .../client/session/ui/header/ChatDockKeys.kt | 8 + .../client/session/ui/header/PrHeaderView.kt | 196 ++++++++++++++++++ .../session/ui/header/SessionHeaderPanel.kt | 65 +----- .../kotlin/ai/kilocode/client/ui/PrBadges.kt | 45 ++++ .../resources/kilo.jetbrains.frontend.xml | 10 + .../resources/messages/KiloBundle.properties | 11 + .../worktree/WorktreePrHeaderViewTest.kt | 2 + .../client/session/SessionUiLayoutTest.kt | 68 +++++- .../client/session/SessionUiTestBase.kt | 3 + .../subagent/SubagentSessionEditorHostTest.kt | 2 +- .../session/ui/header/BranchDockTest.kt | 195 +++++++++++++++++ .../session/ui/header/PrHeaderViewTest.kt | 126 +++++++++++ .../ui/header/SessionHeaderPanelTest.kt | 69 +----- .../client/testing/FakeWorktreeRpcApi.kt | 19 ++ .../ai/kilocode/client/ui/UiStyleTest.kt | 1 - .../ai/kilocode/rpc/KiloWorktreeRpcApi.kt | 17 ++ .../kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt | 26 +++ 38 files changed, 1633 insertions(+), 346 deletions(-) create mode 100644 packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatNewWorktreeAction.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/MoveToWorktree.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/ChatDockKeys.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/PrBadges.kt create mode 100644 packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt create mode 100644 packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt index 8cfe58b3f37a..b9b8b2eea04b 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt @@ -163,6 +163,41 @@ class KiloBackendSessionManager( } } + /** + * Fork session [id] into [dir] via `POST /session/{id}/fork?directory={dir}` with an empty body. + * + * Uses raw HTTP for the same reason as [create]: the generated client sends a malformed empty + * body. The CLI accepts a bodyless fork and `?directory=` overrides the source session directory + * (see packages/opencode/src/kilocode/server/httpapi/session-fork.ts and fork-routing.ts). + */ + fun fork(id: String, dir: String): SessionDto { + val h = http ?: throw IllegalStateException("Session manager not started") + val url = base ?: throw IllegalStateException("Session manager not started") + val target = url.toHttpUrl().newBuilder() + .addPathSegment("session") + .addPathSegment(id) + .addPathSegment("fork") + .addQueryParameter("directory", dir) + .build() + log.info("Forking session: POST $target") + val request = Request.Builder() + .url(target) + .post(ByteArray(0).toRequestBody(null)) + .build() + + h.newCall(request).execute().use { response -> + val raw = response.body?.string() + if (!response.isSuccessful) { + log.warn("Session fork failed: HTTP ${response.code}, body=$raw") + throw RuntimeException("Session fork failed: HTTP ${response.code} — $raw") + } + val dto = KiloCliDataParser.parseSession(raw!!) + log.info("${ChatLogSummary.sid(dto.id)} kind=session forkedFrom=${ChatLogSummary.sid(id)} code=${response.code}") + owned[dto.id] = dto.directory + return dto + } + } + fun get(id: String, dir: String): SessionDto { val all = requireClient().sessionList(directory = dir) val raw = all.firstOrNull { it.id == id } diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt index 7e78ab891eec..c3d78a47cf47 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt @@ -1,11 +1,15 @@ package ai.kilocode.backend.rpc +import ai.kilocode.backend.app.KiloBackendAppService import ai.kilocode.log.KiloLog import ai.kilocode.rpc.KiloWorktreeRpcApi +import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.CreateWorktreeRequestDto import ai.kilocode.rpc.dto.CreateWorktreeResultDto import ai.kilocode.rpc.dto.GhAvailability import ai.kilocode.rpc.dto.GhState +import ai.kilocode.rpc.dto.MoveProgressDto +import ai.kilocode.rpc.dto.MoveStage import ai.kilocode.rpc.dto.RemoveWorktreeResultDto import ai.kilocode.rpc.dto.RenameWorktreeResultDto import ai.kilocode.rpc.dto.WorktreeBranchesDto @@ -21,6 +25,7 @@ import com.intellij.execution.process.CapturingProcessHandler import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.openapi.application.EDT +import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.io.FileUtil @@ -30,6 +35,8 @@ import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext @@ -63,6 +70,7 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi { private val bases = ConcurrentHashMap>() private val prs = ConcurrentHashMap>() + private val branches = ConcurrentHashMap>() private val ghLock = Any() @Volatile private var ghProbe: Timed? = null @@ -178,6 +186,73 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi { dto } + override suspend fun branchStatus(directory: String): BranchStatusDto = withContext(Dispatchers.IO) { + val now = System.currentTimeMillis() + branches[directory]?.takeIf { now - it.time < PR_TTL }?.let { return@withContext it.value } + val root = Path.of(directory).normalize() + val branch = runGit(root, "branch", "--show-current").stdout.trim() + val worktree = isLinkedWorktree(root) + val availability = ghAvailable(root) + val pr = if (availability == GhAvailability.OK && branch.isNotBlank()) { + val out = runGh(root, "pr", "view", branch, "--json", "number,state,isDraft,url,title,headRefName") + // Only accept a PR whose head branch matches the current branch. Guards against gh + // resolving a PR via upstream/remote configuration that isn't for this branch. + if (out.ok && parsePrHeadRef(out.stdout) == branch) parsePr(directory, out.stdout) else null + } else { + null + } + val dto = BranchStatusDto(branch = branch, worktree = worktree, availability = availability, pr = pr) + branches[directory] = Timed(System.currentTimeMillis(), dto) + dto + } + + override suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow = flow { + val base = Path.of(directory).normalize() + LOG.info("worktree move requested: dir=$base session=$sessionId branch=$branch") + emit(MoveProgressDto(MoveStage.CAPTURING)) + val snapshot = withContext(Dispatchers.IO) { WorktreeTransfer.capture(base) } + try { + emit(MoveProgressDto(MoveStage.CREATING)) + val created = withContext(Dispatchers.IO) { + addWorktree(base, branch.trim(), existing = false, baseRef = snapshot.head) + } + val worktree = created.worktree ?: run { + emit(MoveProgressDto(MoveStage.ERROR, error = created.error ?: "Failed to create worktree")) + return@flow + } + val target = Path.of(worktree.path).normalize() + emit(MoveProgressDto(MoveStage.TRANSFERRING)) + val applied = withContext(Dispatchers.IO) { WorktreeTransfer.apply(snapshot, base, target) } + if (!applied.ok) { + LOG.warn("worktree move: rolling back ${worktree.path} after transfer failure") + remove(directory, worktree.path, branch, force = true) + emit(MoveProgressDto(MoveStage.ERROR, error = applied.error ?: "Failed to apply changes to worktree")) + return@flow + } + emit(MoveProgressDto(MoveStage.FORKING)) + val forked = runCatching { + withContext(Dispatchers.IO) { service().sessions.fork(sessionId, worktree.path) } + }.getOrElse { err -> + LOG.warn("worktree move: fork failed session=$sessionId", err) + emit(MoveProgressDto(MoveStage.ERROR, error = err.message ?: "Failed to fork session")) + return@flow + } + LOG.info("worktree move done: worktree=${worktree.path} session=${forked.id}") + emit(MoveProgressDto(MoveStage.DONE, worktree = worktree, session = forked.id)) + } finally { + withContext(Dispatchers.IO) { WorktreeTransfer.cleanup(snapshot) } + } + } + + /** Detects a linked (non-primary) worktree: its git-dir differs from the shared common git-dir. */ + private fun isLinkedWorktree(root: Path): Boolean { + val res = runGit(root, "rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir") + if (!res.ok) return false + val lines = res.stdout.lines().map { it.trim() }.filter { it.isNotEmpty() } + if (lines.size < 2) return false + return Path.of(lines[0]).normalize() != Path.of(lines[1]).normalize() + } + override suspend fun create(directory: String, request: CreateWorktreeRequestDto): CreateWorktreeResultDto = withContext(Dispatchers.IO) { val base = Path.of(directory).normalize() diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt new file mode 100644 index 000000000000..84b5c17dd7e3 --- /dev/null +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt @@ -0,0 +1,157 @@ +package ai.kilocode.backend.rpc + +import ai.kilocode.log.KiloLog +import com.intellij.execution.configurations.GeneralCommandLine +import com.intellij.execution.process.CapturingProcessHandler +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.fileSize + +/** + * Portable git-state snapshot for "Move to Worktree". Captures uncommitted changes as binary-safe + * patch files plus untracked file copies, then applies them to a fresh worktree without ever + * modifying the source working tree. + * + * Ported from `packages/kilo-vscode/src/agent-manager/git-transfer.ts`. Patches are captured to temp + * files with [ProcessBuilder.redirectOutput] rather than decoded to strings: `CapturingProcessHandler` + * decodes stdout with a charset and would corrupt `--binary` patches. + */ +internal object WorktreeTransfer { + private val LOG = KiloLog.create(WorktreeTransfer::class.java) + private const val MAX_FILE = 10L * 1024 * 1024 // 10 MB, same cap as VS Code + private const val TIMEOUT = 30_000 + + /** Read-only snapshot of a working tree. Patch fields point at temp files owned by the caller. */ + data class Snapshot( + val branch: String, + val head: String, + val staged: Path?, + val unstaged: Path?, + val untracked: List, + ) + + data class ApplyResult(val ok: Boolean, val error: String? = null) + + /** + * Captures the current git state from [root]. Read-only: [root] is never modified. The returned + * snapshot owns temp patch files that the caller must delete via [cleanup] in a `finally`. + */ + fun capture(root: Path): Snapshot { + val branch = git(root, "branch", "--show-current").stdout.trim() + val head = git(root, "rev-parse", "HEAD").stdout.trim() + val unstaged = capturePatch(root, "diff", "--binary") + val staged = capturePatch(root, "diff", "--cached", "--binary") + val untracked = git(root, "ls-files", "--others", "--exclude-standard").stdout + .lineSequence() + .map { it.trim() } + .filter { it.isNotEmpty() } + .filter { rel -> + val full = root.resolve(rel).normalize() + if (!full.startsWith(root)) { + LOG.warn("worktree move: skipping untracked file outside root: $rel") + return@filter false + } + val size = runCatching { full.fileSize() }.getOrDefault(0L) + if (size > MAX_FILE) { + LOG.info("worktree move: skipping untracked file $rel: $size bytes exceeds ${MAX_FILE} limit") + false + } else { + true + } + } + .toList() + return Snapshot(branch, head, staged, unstaged, untracked) + } + + /** + * Applies [snapshot] into [target]: staged patch (re-staged), unstaged patch, then untracked + * file copies. Returns the first failure encountered so the caller can roll the worktree back. + */ + fun apply(snapshot: Snapshot, source: Path, target: Path): ApplyResult { + snapshot.staged?.let { patch -> + val res = git(target, "apply", "--whitespace=nowarn", patch.toString()) + if (!res.ok) { + val msg = res.stderr.trim().ifBlank { "Patch did not apply" } + LOG.warn("worktree move: staged patch failed: $msg") + return ApplyResult(false, "Staged patch failed: $msg") + } + val files = parsePatchFiles(patch) + if (files.isNotEmpty()) git(target, "add", "--", *files.toTypedArray()) + } + snapshot.unstaged?.let { patch -> + val res = git(target, "apply", "--whitespace=nowarn", patch.toString()) + if (!res.ok) { + val msg = res.stderr.trim().ifBlank { "Patch did not apply" } + LOG.warn("worktree move: unstaged patch failed: $msg") + return ApplyResult(false, "Unstaged patch failed: $msg") + } + } + for (rel in snapshot.untracked) { + runCatching { + val src = source.resolve(rel).normalize() + val dst = target.resolve(rel).normalize() + Files.createDirectories(dst.parent) + Files.copy(src, dst) + }.onFailure { err -> LOG.warn("worktree move: failed to copy untracked file $rel: ${err.message}", err) } + } + return ApplyResult(true) + } + + fun cleanup(snapshot: Snapshot?) { + snapshot ?: return + listOfNotNull(snapshot.staged, snapshot.unstaged).forEach { Files.deleteIfExists(it) } + } + + /** Runs `git diff` capturing raw bytes to a temp file; returns null when clean or on failure. */ + private fun capturePatch(root: Path, vararg args: String): Path? { + val file = Files.createTempFile("kilo-worktree-patch", ".diff") + return try { + val proc = ProcessBuilder(listOf("git") + args) + .directory(root.toFile()) + .redirectOutput(file.toFile()) + .redirectErrorStream(false) + .start() + val done = proc.waitFor(TIMEOUT.toLong(), java.util.concurrent.TimeUnit.MILLISECONDS) + if (!done) { + proc.destroyForcibly() + Files.deleteIfExists(file) + return null + } + if (proc.exitValue() != 0 || file.fileSize() == 0L) { + Files.deleteIfExists(file) + null + } else { + file + } + } catch (e: Exception) { + LOG.warn("worktree move: capture patch failed: ${e.message}", e) + Files.deleteIfExists(file) + null + } + } + + /** Extracts target paths from a unified diff's `diff --git a/... b/...` headers. */ + private fun parsePatchFiles(patch: Path): List { + // Read as Latin-1 so every byte maps to a char; header lines stay intact even in binary patches. + val header = Regex("^diff --git a/.+ b/(.+)$") + return runCatching { + Files.readAllLines(patch, StandardCharsets.ISO_8859_1) + .mapNotNull { header.find(it)?.groupValues?.get(1) } + }.getOrDefault(emptyList()) + } + + private data class GitResult(val exit: Int, val stdout: String, val stderr: String) { + val ok get() = exit == 0 + } + + private fun git(root: Path, vararg args: String): GitResult { + return try { + val cmd = GeneralCommandLine(listOf("git") + args).withWorkDirectory(root.toFile()) + val out = CapturingProcessHandler(cmd).runProcess(TIMEOUT) + GitResult(if (out.isTimeout) -1 else out.exitCode, out.stdout, out.stderr) + } catch (e: Exception) { + GitResult(-1, "", e.message ?: "git failed") + } + } +} diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendSessionManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendSessionManagerTest.kt index 9943f35c8055..c5fc5433acb0 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendSessionManagerTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendSessionManagerTest.kt @@ -309,6 +309,57 @@ class KiloBackendSessionManagerTest { assertEquals("/test", session.directory) } + // ------ Session fork ------ + + @Test + fun `fork posts to fork endpoint with empty body and directory override`() = runBlocking { + mock.sessionFork = """{ + "id": "ses_forked", + "slug": "forked", + "projectID": "prj_test", + "directory": "/worktree/path", + "title": "Forked", + "version": "1.0.0", + "time": {"created": 1000, "updated": 1000} + }""" + val app = setup() + ready(app) + + val session = app.sessions.fork("ses_source", "/worktree/path") + + assertEquals("ses_forked", session.id) + assertEquals("/worktree/path", session.directory) + val path = mock.lastForkPath ?: error("missing fork request") + assertTrue(path.startsWith("/session/ses_source/fork?"), "Expected fork path, got $path") + assertTrue(URLDecoder.decode(path, "UTF-8").contains("directory=/worktree/path"), path) + // The CLI accepts a bodyless fork; a non-empty body would be rejected. + assertEquals("", mock.lastForkBody) + } + + @Test + fun `fork surfaces server failure`() = runBlocking { + mock.sessionForkStatus = 500 + mock.sessionFork = """{"error":"boom"}""" + val app = setup() + ready(app) + + val err = assertFailsWith { + app.sessions.fork("ses_source", "/worktree") + } + + assertTrue(err.message.orEmpty().contains("HTTP 500")) + assertTrue(err.message.orEmpty().contains("boom")) + } + + @Test + fun `fork throws before start`() = runBlocking { + val app = setup() + + assertFailsWith { + app.sessions.fork("ses_source", "/worktree") + } + } + // ------ Session delete ------ @Test diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt index 4ebba6388ab3..ce5768390f45 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt @@ -442,6 +442,79 @@ class KiloWorktreeRpcApiImplTest { assertEquals("Fix login bug", pull.title) } + @Test + fun `branchStatus reports plain checkout and linked worktree`() = runBlocking { + initRepo() + + val main = api.branchStatus(repo.toString()) + assertFalse(main.worktree, "main checkout is not a linked worktree") + assertTrue(main.branch.isNotBlank(), "main checkout should report a branch") + + val created = assertNotNull(api.create(repo.toString(), CreateWorktreeRequestDto("feature/x")).worktree) + val wt = api.branchStatus(created.path) + assertTrue(wt.worktree, "a linked worktree should be detected") + assertEquals("feature/x", wt.branch) + } + + @Test + fun `worktree transfer round trips changes without touching the source`() = runBlocking { + initRepo() + Files.writeString(repo.resolve("tracked.txt"), "original\n") + git(repo, "add", "tracked.txt") + git(repo, "commit", "-m", "add tracked") + // Staged new file, an unstaged modification to a tracked file, an untracked text file, + // and an untracked binary file. + Files.writeString(repo.resolve("staged.txt"), "staged content\n") + git(repo, "add", "staged.txt") + Files.writeString(repo.resolve("tracked.txt"), "modified\n") + Files.writeString(repo.resolve("untracked.txt"), "brand new\n") + val binary = byteArrayOf(0, 1, 2, 3, 0, 5, 127, -1) + Files.write(repo.resolve("blob.bin"), binary) + + val snapshot = WorktreeTransfer.capture(repo) + val created = assertNotNull(api.create(repo.toString(), CreateWorktreeRequestDto("feature/x")).worktree) + val target = Path.of(created.path) + // Baseline the source status after worktree creation (which adds .kilo bookkeeping) so the + // assertion isolates the effect of apply, which must not touch the source tree. + val before = statusOf(repo) + + val result = WorktreeTransfer.apply(snapshot, repo, target) + assertTrue(result.ok, "apply should succeed: ${result.error}") + + assertEquals("modified\n", Files.readString(target.resolve("tracked.txt"))) + assertEquals("staged content\n", Files.readString(target.resolve("staged.txt"))) + assertEquals("brand new\n", Files.readString(target.resolve("untracked.txt"))) + assertTrue(binary.contentEquals(Files.readAllBytes(target.resolve("blob.bin"))), "binary file should round-trip") + + // The source working tree must be untouched by capture + apply. + assertEquals(before, statusOf(repo), "source working tree must be unchanged") + WorktreeTransfer.cleanup(snapshot) + } + + @Test + fun `worktree transfer reports failure when a staged patch cannot apply`() = runBlocking { + initRepo() + Files.writeString(repo.resolve("staged.txt"), "staged content\n") + git(repo, "add", "staged.txt") + + val snapshot = WorktreeTransfer.capture(repo) + val created = assertNotNull(api.create(repo.toString(), CreateWorktreeRequestDto("feature/x")).worktree) + val target = Path.of(created.path) + // Pre-create the staged file in the target so the new-file patch cannot apply cleanly. + Files.writeString(target.resolve("staged.txt"), "conflicting\n") + + val result = WorktreeTransfer.apply(snapshot, repo, target) + + assertFalse(result.ok, "apply should fail when the patch conflicts") + assertNotNull(result.error) + WorktreeTransfer.cleanup(snapshot) + } + + private fun statusOf(dir: Path): String { + val cmd = GeneralCommandLine(listOf("git", "status", "--porcelain")).withWorkDirectory(dir.toFile()) + return CapturingProcessHandler(cmd).runProcess(30_000).stdout + } + private fun initRepo() { git(repo, "init") git(repo, "config", "user.email", "test@kilo.ai") diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/testing/MockCliServer.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/testing/MockCliServer.kt index 1d35de360a2c..bd14d42d6868 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/testing/MockCliServer.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/testing/MockCliServer.kt @@ -104,6 +104,10 @@ class MockCliServer : AutoCloseable { @Volatile var sessions = "[]" @Volatile var recentSessions = "[]" @Volatile var sessionCreate = """{"id":"ses_test","slug":"test","projectID":"prj_test","directory":"/test","title":"New Session","version":"1.0.0","time":{"created":1000,"updated":1000}}""" + @Volatile var sessionFork = """{"id":"ses_forked","slug":"forked","projectID":"prj_test","directory":"/worktree","title":"Forked Session","version":"1.0.0","time":{"created":1000,"updated":1000}}""" + @Volatile var sessionForkStatus = 200 + @Volatile var lastForkPath: String? = null + @Volatile var lastForkBody: String? = null @Volatile var sessionStatuses = "{}" @Volatile var sessionDiff = "[]" @Volatile var lastSessionDiffPath: String? = null @@ -442,6 +446,11 @@ class MockCliServer : AutoCloseable { lastSessionRenameMethod = method respond(output, sessionRenameStatus, sessionRenameResponse) } + bare.matches(Regex("/session/ses_[^/]+/fork")) && method == "POST" -> { + lastForkPath = path + lastForkBody = body + respond(output, sessionForkStatus, sessionFork) + } bare.matches(Regex("/session/ses_[^/]+/diff")) && method == "GET" -> { lastSessionDiffPath = path respond(output, 200, sessionDiff) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt index 2f3b9aa35917..9cc0c3f60925 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt @@ -138,6 +138,14 @@ internal class KiloToolWindowSetupService( agentContent.putUserData(ToolWindow.SHOW_CONTENT_ICON, true) toolWindow.contentManager.addContent(chatContent) toolWindow.contentManager.addContent(agentContent) + // The chat branch dock's "New Worktree" action switches to the Agent Manager tab and + // opens its New Worktree dialog, matching the VS Code sidebar dock. + manager.onNewWorktree = { + Telemetry.send("New Worktree Clicked", mapOf("surface" to "chat_dock")) + agentManagerPanel.configure { + toolWindow.contentManager.setSelectedContent(agentContent) + } + } val listener = object : ContentManagerListener { override fun selectionChanged(event: ContentManagerEvent) { if (event.operation == ContentManagerEvent.ContentOperation.add && event.content === agentContent) { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt new file mode 100644 index 000000000000..b368d73c0b4e --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt @@ -0,0 +1,64 @@ +package ai.kilocode.client.actions + +import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.session.ui.header.ChatDockKeys +import ai.kilocode.rpc.dto.MoveStage +import com.intellij.openapi.actionSystem.ActionUpdateThread +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.ex.ActionUtil +import com.intellij.openapi.project.DumbAware +import com.intellij.openapi.util.IconLoader +import com.intellij.ui.AnimatedIcon + +/** + * "Move to Worktree" action shown in the chat branch dock. Visible only when there is something to + * move (a conversation or local changes). While a move runs it stays visible but disabled, showing a + * spinner and the current stage. + */ +class ChatMoveToWorktreeAction : AnAction(), DumbAware { + override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT + + override fun update(e: AnActionEvent) { + e.presentation.putClientProperty(ActionUtil.SHOW_TEXT_IN_TOOLBAR, true) + val dock = e.getData(ChatDockKeys.DOCK) + if (dock == null) { + e.presentation.isEnabledAndVisible = false + return + } + if (dock.moving()) { + e.presentation.isVisible = true + e.presentation.isEnabled = false + e.presentation.icon = AnimatedIcon.Default.INSTANCE + e.presentation.text = progressLabel(dock.moveStage()) + e.presentation.description = null + return + } + e.presentation.isEnabledAndVisible = dock.moveEnabled() + e.presentation.icon = BRANCH + e.presentation.text = KiloBundle.message("session.dock.move") + e.presentation.description = moveTooltip(dock.changeCount()) + } + + override fun actionPerformed(e: AnActionEvent) { + e.getData(ChatDockKeys.DOCK)?.triggerMove() + } + + private fun progressLabel(stage: MoveStage?): String = when (stage) { + MoveStage.CAPTURING -> KiloBundle.message("session.dock.progress.capturing") + MoveStage.CREATING -> KiloBundle.message("session.dock.progress.creating") + MoveStage.TRANSFERRING -> KiloBundle.message("session.dock.progress.transferring") + MoveStage.FORKING -> KiloBundle.message("session.dock.progress.forking") + else -> KiloBundle.message("session.dock.move") + } + + private fun moveTooltip(count: Int): String = when (count) { + 0 -> KiloBundle.message("session.dock.move.tooltip.empty") + 1 -> KiloBundle.message("session.dock.move.tooltip.one") + else -> KiloBundle.message("session.dock.move.tooltip.other", count) + } + + private companion object { + private val BRANCH = IconLoader.getIcon("/icons/worktreeBranch.svg", ChatMoveToWorktreeAction::class.java) + } +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatNewWorktreeAction.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatNewWorktreeAction.kt new file mode 100644 index 000000000000..ec78e8dbb877 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatNewWorktreeAction.kt @@ -0,0 +1,31 @@ +package ai.kilocode.client.actions + +import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.session.ui.header.ChatDockKeys +import com.intellij.icons.AllIcons +import com.intellij.openapi.actionSystem.ActionUpdateThread +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.ex.ActionUtil +import com.intellij.openapi.project.DumbAware + +/** + * "New Worktree" action shown in the chat branch dock. Visible only while the dock is active (the + * session has a conversation or local changes), so it never appears on its own in an empty session. + */ +class ChatNewWorktreeAction : AnAction(), DumbAware { + override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT + + override fun update(e: AnActionEvent) { + val dock = e.getData(ChatDockKeys.DOCK) + e.presentation.isEnabledAndVisible = dock?.newWorktreeEnabled() == true + e.presentation.icon = AllIcons.General.Add + e.presentation.text = KiloBundle.message("session.dock.newWorktree") + e.presentation.description = KiloBundle.message("session.dock.newWorktree.tooltip") + e.presentation.putClientProperty(ActionUtil.SHOW_TEXT_IN_TOOLBAR, true) + } + + override fun actionPerformed(e: AnActionEvent) { + e.getData(ChatDockKeys.DOCK)?.triggerNewWorktree() + } +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 00a8620003ae..1765da0e001a 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -14,10 +14,10 @@ import ai.kilocode.client.agentManager.worktree.WorktreeSessionEditorMatcher import ai.kilocode.client.agentManager.worktree.WorktreeSessionEditorKind import ai.kilocode.client.agentManager.worktree.WorktreeTitle import ai.kilocode.client.agentManager.worktree.ensureWorktreeSessionEditorKind -import ai.kilocode.client.agentManager.worktree.prTooltip import ai.kilocode.client.agentManager.worktree.normalizeWorktreePath -import ai.kilocode.client.agentManager.worktree.style import ai.kilocode.client.agentManager.worktree.worktreeSessionParams +import ai.kilocode.client.ui.prTooltip +import ai.kilocode.client.ui.style import ai.kilocode.client.diff.KiloDiffEditorKind import ai.kilocode.client.diff.diffParams import ai.kilocode.client.diff.ensureDiffEditorKind @@ -155,7 +155,7 @@ class AgentManagerPanel( } /** Opens the New Worktree dialog. */ - fun configure() { + fun configure(afterClose: (() -> Unit)? = null) { val target = project ?: return NewWorktreeDialog( this, @@ -168,6 +168,7 @@ class AgentManagerPanel( controller.create(branch, base, prompt = prompt) }, ).show() + afterClose?.invoke() } private fun remove(item: WorktreeDto, force: Boolean) { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt index 6cf40e280edf..832dd8d12512 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt @@ -4,9 +4,11 @@ package ai.kilocode.client.agentManager.worktree import ai.kilocode.log.KiloLog import ai.kilocode.rpc.KiloWorktreeRpcApi +import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.CreateWorktreeRequestDto import ai.kilocode.rpc.dto.CreateWorktreeResultDto import ai.kilocode.rpc.dto.GhAvailability +import ai.kilocode.rpc.dto.MoveProgressDto import ai.kilocode.rpc.dto.RemoveWorktreeResultDto import ai.kilocode.rpc.dto.RenameWorktreeResultDto import ai.kilocode.rpc.dto.WorktreeBranchesDto @@ -17,6 +19,7 @@ import com.intellij.openapi.components.Service import fleet.rpc.client.durable import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch /** @@ -97,6 +100,20 @@ class KiloWorktreeService internal constructor( WorktreePrListDto() } + suspend fun branchStatus(directory: String): BranchStatusDto = try { + call { branchStatus(directory) } + } catch (e: Exception) { + LOG.warn("worktree branch status failed for $directory", e) + BranchStatusDto() + } + + /** + * Long-lived move flow. Routed through [durable] (via [call]) so it survives reconnects and + * backend restarts while the move runs. + */ + suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow = + call { moveToWorktree(directory, sessionId, branch) } + suspend fun create(directory: String, req: CreateWorktreeRequestDto): CreateWorktreeResultDto = call { create(directory, req) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/MoveToWorktree.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/MoveToWorktree.kt new file mode 100644 index 000000000000..55f79a3510fe --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/MoveToWorktree.kt @@ -0,0 +1,72 @@ +package ai.kilocode.client.agentManager.worktree + +import ai.kilocode.client.KiloNotifications +import ai.kilocode.client.app.KiloSessionService +import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.telemetry.Telemetry +import ai.kilocode.client.vfs.KiloVfsManager +import ai.kilocode.log.KiloLog +import ai.kilocode.rpc.dto.MoveProgressDto +import ai.kilocode.rpc.dto.MoveStage +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project +import com.intellij.util.concurrency.annotations.RequiresEdt +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * Sidebar "Move to Worktree": aborts the running session, generates a friendly branch name, then + * drives the backend move flow (capture → create → transfer → fork). On success it opens the + * worktree session editor on the forked session; on error it notifies through the worktree pattern. + * The source sidebar session stays in the sidebar (aborted, not deleted), matching VS Code fork + * semantics. + */ +internal class MoveToWorktree( + private val project: Project, + private val cs: CoroutineScope, +) { + private companion object { + private val LOG = KiloLog.create(MoveToWorktree::class.java) + } + + /** [progress] is invoked on the EDT for each stage so the dock button can reflect it. */ + @RequiresEdt + fun launch(directory: String, sessionId: String, progress: (MoveStage, String?) -> Unit) { + cs.launch { + runCatching { service().abort(sessionId, directory) } + .onFailure { LOG.info("worktree move: abort failed (session may be idle): ${it.message}") } + val known = service().listBranches(directory).branches.toSet() + val branch = WorktreeNames.generate(known) + var stage = MoveStage.CAPTURING + val flow = service().moveToWorktree(directory, sessionId, branch) + flow.collect { event -> + if (event.stage != MoveStage.ERROR) stage = event.stage + withContext(Dispatchers.Main) { handle(event, stage, progress) } + } + } + } + + @RequiresEdt + private fun handle(event: MoveProgressDto, failing: MoveStage, progress: (MoveStage, String?) -> Unit) { + progress(event.stage, event.detail) + when (event.stage) { + MoveStage.DONE -> { + val worktree = event.worktree ?: return + ensureWorktreeSessionEditorKind() + project.service().open( + WorktreeSessionEditorKind.ID, + worktreeSessionParams(worktree, session = event.session), + ) + Telemetry.send("Continue in Worktree", mapOf("surface" to "sidebar")) + } + MoveStage.ERROR -> { + LOG.warn("worktree move failed stage=$failing error=${event.error}") + KiloNotifications.error(project, KiloBundle.message("session.dock.move.failed.title"), event.error) + Telemetry.send("Continue in Worktree Failed", mapOf("stage" to failing.name)) + } + else -> Unit + } + } +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt index 79fc3650bcba..dcce0e600d31 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt @@ -1,40 +1,27 @@ package ai.kilocode.client.agentManager.worktree import ai.kilocode.client.plugin.KiloBundle -import ai.kilocode.client.session.ui.header.BranchChangesBadge -import ai.kilocode.client.session.ui.style.SessionEditorStyle -import ai.kilocode.client.ui.FilledBadgeIcon +import ai.kilocode.client.session.ui.header.PrHeaderView import ai.kilocode.client.ui.ToolbarButtonAction -import ai.kilocode.client.ui.UiStyle import ai.kilocode.client.ui.hoverTextButton -import ai.kilocode.client.ui.layout.HAlign -import ai.kilocode.client.ui.layout.Stack -import ai.kilocode.client.ui.layout.VAlign -import ai.kilocode.client.ui.layout.align -import ai.kilocode.rpc.dto.GhState import ai.kilocode.rpc.dto.WorktreePrDto import ai.kilocode.rpc.dto.WorktreeStatsDto -import com.intellij.ide.BrowserUtil import com.intellij.ide.ui.ProductIcons -import com.intellij.ui.SimpleColoredComponent -import com.intellij.ui.SimpleTextAttributes -import com.intellij.ui.components.JBLabel import com.intellij.util.concurrency.annotations.RequiresEdt -import com.intellij.util.ui.JBUI -import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.plugins.terminal.TerminalIcons -import java.awt.BorderLayout -import java.awt.Cursor -import java.awt.event.MouseAdapter -import java.awt.event.MouseEvent +/** + * Worktree session editor header. A thin wrapper over the shared [PrHeaderView] that adds the + * Terminal and Open-in-window actions into the header's trailing slot. + */ internal class WorktreePrHeaderView( openWorktree: () -> Unit = {}, openEnabled: Boolean = true, openTerminal: () -> Unit = {}, openDiff: () -> Unit, ) : BorderLayoutPanel() { + private val core = PrHeaderView(openDiff) private val terminal = hoverTextButton( ToolbarButtonAction(TerminalIcons.OpenTerminal_13x13, KiloBundle.message("worktree.session.terminal.action"), openTerminal), tooltip = KiloBundle.message("worktree.session.terminal.tooltip"), @@ -43,128 +30,18 @@ internal class WorktreePrHeaderView( ToolbarButtonAction(ProductIcons.getInstance().productIcon, KiloBundle.message("worktree.session.open.action"), openWorktree), tooltip = KiloBundle.message("worktree.session.open.tooltip"), ) - private val status = JBLabel() - private val title = SimpleColoredComponent() - private val changes = BranchChangesBadge(openDiff).apply { applyStyle(SessionEditorStyle.current()) } - private val statusPane = status.align(HAlign.LEFT, VAlign.CENTER) - private val actions = Stack.horizontal(UiStyle.Gap.sm()) - .next(changes.align(HAlign.CENTER, VAlign.CENTER)) - .next(terminal.align(HAlign.CENTER, VAlign.CENTER)) - .next(open.align(HAlign.CENTER, VAlign.CENTER)) - private var pull: WorktreePrDto? = null - private var state: GhState? = null - private var text: String? = null - private var tip: String? = null - private var url: String? = null init { isOpaque = false - actions.isOpaque = false open.isEnabled = openEnabled terminal.isEnabled = openEnabled - actions.border = JBUI.Borders.emptyRight(UiStyle.Gap.sm()) - status.border = JBUI.Borders.empty(0, UiStyle.Gap.md(), 0, UiStyle.Gap.xs()) - title.border = JBUI.Borders.empty(0, UiStyle.Gap.sm()) - title.isOpaque = false - addToLeft(statusPane) - addToCenter(title) - addToRight(actions.align(HAlign.RIGHT, VAlign.CENTER)) - val listener = object : MouseAdapter() { - override fun mouseClicked(event: MouseEvent) { - url?.let(BrowserUtil::browse) - } - } - status.addMouseListener(listener) - title.addMouseListener(listener) - syncClick(null) + core.addAction(terminal) + core.addAction(open) + addToCenter(core) } @RequiresEdt fun update(stats: WorktreeStatsDto?, pull: WorktreePrDto?, name: String) { - changes.update(stats?.files ?: 0, stats?.additions ?: 0, stats?.deletions ?: 0) - this.pull = pull - if (pull == null) { - syncPr(false) - syncStatus(null) - clearTitle() - syncClick(null) - return - } - syncPr(true) - val title = pull.title.trim() - val text = if (title.isBlank()) null else title - val tip = prTooltip(pull, name.takeIf { it.isNotBlank() && it != pull.title.trim() }) - syncStatus(pull.state) - syncTitle("#${pull.number}", text, tip) - syncClick(pull.url) - status.toolTipText = tip - } - - private fun syncStatus(next: GhState?) { - if (state == next) { - val visible = next != null - if (status.isVisible != visible) status.isVisible = visible - return - } - state = next - status.icon = next?.let { FilledBadgeIcon(stateLabel(it), style(it)) } - status.isVisible = next != null - changed() - } - - private fun syncPr(value: Boolean) { - if (value) { - if (title.parent !== this) add(title, BorderLayout.CENTER) - title.isVisible = true - return - } - title.isVisible = false - changed() - } - - private fun clearTitle() { - if (text == null && tip == null) return - text = null - tip = null - title.clear() - title.toolTipText = null - status.toolTipText = null - changed() - } - - private fun syncTitle(number: String, next: String?, nextTip: String?) { - val full = listOfNotNull(next, number).joinToString(" ") - var changed = false - if (text != full) { - text = full - title.clear() - if (next == null) { - title.append(number, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) - } else { - title.append(next, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) - title.append(" $number", SimpleTextAttributes.GRAYED_ATTRIBUTES) - } - changed = true - } - if (tip != nextTip) { - tip = nextTip - title.toolTipText = nextTip - if (pull == null) status.toolTipText = null - changed = true - } - if (changed) changed() - } - - private fun syncClick(next: String?) { - if (url == next) return - url = next - val cursor = if (next != null) Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) else Cursor.getDefaultCursor() - status.cursor = cursor - title.cursor = cursor - } - - private fun changed() { - revalidate() - repaint() + core.update(stats, pull, name) } } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt index 9692044292a7..e5c263405528 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt @@ -38,15 +38,17 @@ object WorktreeSessionEditorKind : KiloEditorKind { @RequiresEdt override fun createContent(project: Project, file: KiloVirtualFile, parent: Disposable): JComponent { val path = file.path.params[PATH]?.takeIf { it.isNotBlank() } ?: return BorderLayoutPanel() + val session = file.path.params[SESSION]?.takeIf { it.isNotBlank() } val worktree = service().workspace(path) val cs = service().scope() Disposer.register(parent) { cs.cancel() } val controller = WorktreeSessionListController(project.service(), path, cs) - val manager = WorktreeSessionEditorManager(parent, project, worktree, controller) + val manager = WorktreeSessionEditorManager(parent, project, worktree, controller, session = session) return WorktreeSessionEditorPanel(parent, manager, controller, worktree, project) } private const val PATH = "path" + private const val SESSION = "session" } fun ensureWorktreeSessionEditorKind() { @@ -57,6 +59,6 @@ internal fun unregisterWorktreeSessionEditorKind() { service().unregister(WorktreeSessionEditorKind.ID) } -internal fun worktreeSessionParams(item: WorktreeDto): Map = linkedMapOf( +internal fun worktreeSessionParams(item: WorktreeDto, session: String? = null): Map = linkedMapOf( "path" to item.path, -) +).apply { session?.takeIf { it.isNotBlank() }?.let { put("session", it) } } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorManager.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorManager.kt index 4ce07d5147f0..e90494509fa4 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorManager.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorManager.kt @@ -46,6 +46,7 @@ open class WorktreeSessionEditorManager( project: Project, private val worktree: Workspace, private val list: WorktreeSessionListController, + private val session: String? = null, private val del: (String, (Boolean, String?) -> Unit) -> Unit = list::delete, create: (Project, Workspace, SessionManager, SessionRef?, UiTimerSource) -> SessionUi = { project, workspace, manager, ref, timers -> @@ -72,7 +73,7 @@ open class WorktreeSessionEditorManager( } }, ) : SessionHost(project, worktree, create, resolve, status, timers, request) { - override val showsBranchBadgeInHeader: Boolean get() = false + override val showsBranchDock: Boolean get() = false override val hostedInEditorTab: Boolean get() = true private val right = JPanel(BorderLayout()) private val deleting = linkedSetOf() @@ -97,6 +98,11 @@ open class WorktreeSessionEditorManager( fun start() { startedOnce = true list.reload { + val target = session + if (target != null) { + openSession(SessionRef.Local(target), false) + return@reload + } val dto = latest() if (dto != null) openSession(SessionRef.Local(dto), false) else newSession(false) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeStatsView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeStatsView.kt index 7707b8fa0768..6dfabc84cc4f 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeStatsView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeStatsView.kt @@ -9,7 +9,8 @@ import ai.kilocode.client.ui.list.ACTIVE_LIST_PR_CELL import ai.kilocode.client.ui.list.ActiveListBadge import ai.kilocode.client.ui.list.ActiveListHitCell import ai.kilocode.client.ui.layout.Stack -import ai.kilocode.rpc.dto.GhState +import ai.kilocode.client.ui.prTooltip +import ai.kilocode.client.ui.style import ai.kilocode.rpc.dto.WorktreePrDto import ai.kilocode.rpc.dto.WorktreeStatsDto import com.intellij.ide.BrowserUtil @@ -17,7 +18,6 @@ import com.intellij.openapi.util.IconLoader import com.intellij.ui.components.JBLabel import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI -import com.intellij.xml.util.XmlStringUtil import java.awt.BorderLayout import java.awt.Component import java.awt.Container @@ -183,36 +183,3 @@ internal class WorktreeStatsView( override fun cellAction(): (() -> Unit)? = act } } - -internal fun style(state: GhState): UiStyle.Badge.Style = when (state) { - GhState.OPEN -> UiStyle.Badge.PullRequestOpen - GhState.DRAFT -> UiStyle.Badge.PullRequestDraft - GhState.MERGED -> UiStyle.Badge.PullRequestMerged - GhState.CLOSED -> UiStyle.Badge.PullRequestClosed -} - -internal fun stateLabel(state: GhState): String = when (state) { - GhState.OPEN -> KiloBundle.message("worktree.pr.state.open") - GhState.DRAFT -> KiloBundle.message("worktree.pr.state.draft") - GhState.MERGED -> KiloBundle.message("worktree.pr.state.merged") - GhState.CLOSED -> KiloBundle.message("worktree.pr.state.closed") -} - -internal fun prTooltip(pull: WorktreePrDto, name: String? = null): String { - val title = pull.title.trim() - val head = buildString { - append(stateLabel(pull.state)) - append(" #") - append(pull.number) - if (title.isNotBlank()) { - append(' ') - append(title) - } - } - val lines = listOfNotNull( - head, - name?.takeIf { title.isNotBlank() }?.let { "($it)" }, - KiloBundle.message("worktree.pr.tooltip.open"), - ).map(XmlStringUtil::escapeString) - return XmlStringUtil.wrapInHtml(lines.joinToString("
")) -} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt index 32e788ce4353..b3404a7106fe 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt @@ -15,6 +15,12 @@ interface SessionManager { fun newSession() + /** Whether this surface can open the New Worktree flow (sidebar only). */ + val supportsNewWorktree: Boolean get() = false + + /** Opens the New Worktree flow. No-op unless [supportsNewWorktree] is true. */ + fun newWorktree() {} + fun showHistory(back: (() -> Unit)? = null) fun openSession(ref: SessionRef) @@ -27,7 +33,7 @@ interface SessionManager { fun focusPrompt() {} - val showsBranchBadgeInHeader: Boolean get() = true + val showsBranchDock: Boolean get() = true val hostedInEditorTab: Boolean get() = false diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt index 5c5eea292561..6a7714e4b241 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt @@ -49,6 +49,15 @@ class SessionSidePanelManager( private var panel: JComponent? = null private var historyBack: (() -> Unit)? = null + /** Wired by the tool window to open the Agent Manager's New Worktree flow from the chat dock. */ + var onNewWorktree: (() -> Unit)? = null + + override val supportsNewWorktree: Boolean get() = onNewWorktree != null + + override fun newWorktree() { + onNewWorktree?.invoke() + } + val defaultFocusedComponent: JComponent? get() = currentUi()?.defaultFocusedComponent ?: (panel as? HistoryPanel)?.defaultFocusedComponent @RequiresEdt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt index 615548976bc5..edb1ce251db6 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt @@ -43,6 +43,9 @@ import ai.kilocode.client.session.ui.attachment.AttachmentEditorKind import ai.kilocode.client.session.ui.attachment.attachmentParams import ai.kilocode.client.session.ui.attachment.ensureAttachmentEditorKind import ai.kilocode.client.session.ui.attachment.isEmbeddedAttachment +import ai.kilocode.client.agentManager.worktree.KiloWorktreeService +import ai.kilocode.client.agentManager.worktree.MoveToWorktree +import ai.kilocode.client.session.ui.header.BranchDock import ai.kilocode.client.session.ui.header.SessionHeaderPanel import ai.kilocode.client.session.ui.selection.SessionContextMenu import ai.kilocode.client.session.ui.selection.SessionHoverCopyOverlay @@ -50,6 +53,7 @@ import ai.kilocode.client.session.ui.selection.SessionSelection import ai.kilocode.client.session.ui.style.SessionEditorStyle import ai.kilocode.client.session.ui.style.SessionEditorStyleTarget import ai.kilocode.client.ui.layout.HAlign +import ai.kilocode.client.ui.layout.Stack import ai.kilocode.client.ui.layout.VAlign import ai.kilocode.client.ui.layout.align import ai.kilocode.client.session.controller.EVENT_FLUSH_MS @@ -193,6 +197,12 @@ class SessionUi( private lateinit var header: SessionHeaderPanel + private var dock: BranchDock? = null + + private var bottom: JComponent? = null + + private val move by lazy { MoveToWorktree(project, cs) } + internal lateinit var scroll: SessionScroll private lateinit var question: QuestionView @@ -224,6 +234,7 @@ class SessionUi( // but never cancel an in-flight user-initiated open. private var refreshJob: Job? = null private var openJob: Job? = null + private var branchJob: Job? = null private var disposed = false init { @@ -236,7 +247,11 @@ class SessionUi( bindStyle() bindMigration() onStateChanged(controller.model.state) - if (showBranchBadge()) refreshBranchChanges() + dock?.let { + it.setHasMessages(controller.model.messages().isNotEmpty()) + refreshBranchChanges() + refreshBranch() + } loaded?.let(::finishOpen) } @@ -411,7 +426,12 @@ class SessionUi( it.setDiffOpener(::openInlineDiff, controller.id) it.onHover = { view, on -> if (on) popup.show(view) else popup.notifyExit(view) } } - header = SessionHeaderPanel(controller, this, readonly) { openBranchChanges() } + header = SessionHeaderPanel(controller, this, readonly) + if (!readonly && showBranchDock()) { + val owner = manager + val newWorktree = if (owner?.supportsNewWorktree == true) owner::newWorktree else null + dock = BranchDock(openDiff = ::openBranchChanges, onMove = ::moveToWorktree, onNewWorktree = newWorktree) + } scroll = SessionScroll(root, sessionContent, messageBody, blankBody) overlay = SessionHoverCopyOverlay(root, scroll.component, this) @@ -457,12 +477,16 @@ class SessionUi( val point = SwingUtilities.convertPoint(prompt.parent ?: root.content, prompt.x, prompt.y, pane) val gap = SessionUiStyle.View.contentGap() val wide = (prompt.width - gap * 2).coerceAtLeast(0) + // Anchor above the whole bottom container (dock + prompt) so the banner floats over the + // dock rather than covering it; fall back to the prompt when there is no dock. + val anchor = bottom ?: prompt + val topY = SwingUtilities.convertPoint(anchor.parent ?: root.content, anchor.x, anchor.y, pane).y // Fix the banner width before measuring so its word-wrapped detail height is known. child.setSize(wide, child.height) - val height = child.preferredSize.height.coerceAtMost((point.y - gap).coerceAtLeast(0)) + val height = child.preferredSize.height.coerceAtMost((topY - gap).coerceAtLeast(0)) java.awt.Rectangle( point.x + gap, - point.y - height - gap, + topY - height - gap, wide, height, ) @@ -484,14 +508,22 @@ class SessionUi( sessionContent.add(scroll.component, BorderLayout.CENTER) root.content.add(sessionContent, BorderLayout.CENTER) if (!readonly) { - root.content.add( + // In the sidebar tool window the bottom panel fills the full width; editor tabs keep the + // readable-width centering used across the transcript. + val aligned = if (manager?.hostedInEditorTab == true) { prompt.align( HAlign.CENTER, VAlign.FIT, maxW = { SessionUiStyle.SessionLayout.readableWidth(prompt, style.transcriptFont) }, - ), - BorderLayout.SOUTH, - ) + ) + } else { + prompt.align(HAlign.FIT, VAlign.FIT) + } + val container = Stack.vertical() + dock?.let { container.next(it) } + container.next(aligned) + bottom = container + root.content.add(container, BorderLayout.SOUTH) } add(root, BorderLayout.CENTER) } @@ -611,28 +643,34 @@ class SessionUi( is SessionModelEvent.RevertChanged -> onRevertChanged(event.revert) + is SessionModelEvent.MessageAdded, + is SessionModelEvent.MessageRemoved, + is SessionModelEvent.HistoryLoaded, + is SessionModelEvent.Cleared -> syncDockMessages() + is SessionModelEvent.QueueChanged -> Unit is SessionModelEvent.TurnAdded, is SessionModelEvent.TurnUpdated, is SessionModelEvent.ContentAdded, is SessionModelEvent.ContentDelta, - is SessionModelEvent.HistoryLoaded, is SessionModelEvent.TurnRemoved, - is SessionModelEvent.MessageAdded, is SessionModelEvent.MessageUpdated, - is SessionModelEvent.MessageRemoved, is SessionModelEvent.ContentUpdated, is SessionModelEvent.ContentRemoved, is SessionModelEvent.DiffUpdated, is SessionModelEvent.TodosUpdated, is SessionModelEvent.HeaderUpdated, - is SessionModelEvent.Compacted, - is SessionModelEvent.Cleared -> Unit + is SessionModelEvent.Compacted -> Unit } } } + @RequiresEdt + private fun syncDockMessages() { + dock?.setHasMessages(controller.model.messages().isNotEmpty()) + } + @RequiresEdt private fun syncDrop(value: Boolean) { if (disposed) return @@ -677,7 +715,7 @@ class SessionUi( private fun bindStyle() { addHierarchyListener { event -> if ((event.changeFlags and HierarchyEvent.SHOWING_CHANGED.toLong()) == 0L) return@addHierarchyListener - if (!isShowing) popup.hideAll() + if (isShowing) refreshBranch() else popup.hideAll() } val bus = ApplicationManager.getApplication().messageBus.connect(this) @@ -913,13 +951,9 @@ class SessionUi( Telemetry.send("Subagent Session Opened", mapOf("sessionId" to sessionId)) } - /** Badge-only refresh: fetches stats (no patch text) and updates the header count. */ + /** Badge-only refresh: fetches stats (no patch text) and updates the dock's changes badge. */ private fun refreshBranchChanges() { - if (!showBranchBadge()) { - refreshJob?.cancel() - header.hideBranchChanges() - return - } + val dock = dock ?: return refreshJob?.cancel() refreshJob = cs.launch { val files = runCatching { workspaces.branchDiff(workspace.directory, patches = false) } @@ -930,14 +964,14 @@ class SessionUi( } withContext(Dispatchers.Main) { if (disposed || project.isDisposed) return@withContext - header.setBranchChanges(files) + dock.setChanges(files) } } } /** User clicked the badge: opens the branch diff editor. Never cancelled by a background refresh. */ private fun openBranchChanges() { - if (!showBranchBadge()) return + val dock = dock ?: return openJob?.cancel() openJob = cs.launch { val dir = workspace.directory @@ -950,12 +984,20 @@ class SessionUi( } withContext(Dispatchers.Main) { if (disposed || project.isDisposed) return@withContext - header.setBranchChanges(files) + dock.setChanges(files) openBranchDiff(branch) } } } + /** Starts the Move to Worktree flow for the current session, wiring progress into the dock. */ + @RequiresEdt + private fun moveToWorktree() { + val dock = dock ?: return + val id = controller.id ?: return + move.launch(controller.sessionDirectory, id) { stage, detail -> dock.setMoveProgress(stage, detail) } + } + @RequiresEdt private fun openBranchDiff(branch: String?) { // No store seeding: the diff editor's fetch recomputes branchDiff authoritatively, so a @@ -971,7 +1013,29 @@ class SessionUi( Telemetry.send("Diff Editor Opened", mapOf("source" to "branch")) } - private fun showBranchBadge(): Boolean = manager?.showsBranchBadgeInHeader != false + private fun showBranchDock(): Boolean = manager?.showsBranchDock != false + + /** + * Refreshes the branch/PR status feeding the dock. Uses the session's own [workspace] directory + * (the resolved backend path) — not `project.basePath`, which is a synthetic frontend path in + * split mode — so the PR always matches the branch checked out in this session's directory. + */ + private fun refreshBranch() { + val dock = dock ?: return + branchJob?.cancel() + branchJob = cs.launch { + val status = runCatching { service().branchStatus(workspace.directory) } + .getOrElse { + if (it is CancellationException) throw it + LOG.warn("branch status refresh failed dir=${workspace.directory}", it) + return@launch + } + withContext(Dispatchers.Main) { + if (disposed || project.isDisposed) return@withContext + dock.setBranch(status) + } + } + } private fun openAttachment(messageId: String, item: FileAttachment) { val url = item.url.takeIf { it.isNotBlank() } ?: run { @@ -1033,7 +1097,10 @@ class SessionUi( private fun onStateChanged(state: SessionState) { if (disposed) return val busy = state.isBusy() - if (wasBusy && state is SessionState.Idle) refreshBranchChanges() + if (wasBusy && state is SessionState.Idle) { + refreshBranchChanges() + refreshBranch() + } wasBusy = busy if (state is SessionState.Reverting) overlay.clear() if (state is SessionState.Error || state is SessionState.TurnEnded) { @@ -1065,6 +1132,7 @@ class SessionUi( selection.applyStyle(style) load.applyStyle(style) header.applyStyle(style) + dock?.applyStyle(style) prompt.applyStyle(style) connection.applyStyle(style) scroll.applyStyle(style) @@ -1096,6 +1164,7 @@ class SessionUi( disposed = true refreshJob?.cancel() openJob?.cancel() + branchJob?.cancel() hide.stop() popup.hideAll() modalFocus = null diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/subagent/SubagentSessionEditorHost.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/subagent/SubagentSessionEditorHost.kt index 86ec8580fe55..4d9abdfaa5ca 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/subagent/SubagentSessionEditorHost.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/subagent/SubagentSessionEditorHost.kt @@ -44,7 +44,7 @@ class SubagentSessionEditorHost( ) : SessionHost(project, workspace, create, resolve, status, timers, request) { override val readonly: Boolean get() = true override val hostedInEditorTab: Boolean get() = true - override val showsBranchBadgeInHeader: Boolean get() = false + override val showsBranchDock: Boolean get() = false val component = JPanel(BorderLayout()) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt new file mode 100644 index 000000000000..f11b391bc001 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt @@ -0,0 +1,183 @@ +package ai.kilocode.client.session.ui.header + +import ai.kilocode.client.session.ui.style.SessionEditorStyle +import ai.kilocode.client.session.ui.style.SessionEditorStyleTarget +import ai.kilocode.client.session.ui.style.SessionUiStyle +import ai.kilocode.client.ui.UiStyle +import ai.kilocode.client.ui.layout.HAlign +import ai.kilocode.client.ui.layout.Stack +import ai.kilocode.client.ui.layout.VAlign +import ai.kilocode.client.ui.layout.align +import ai.kilocode.rpc.dto.BranchStatusDto +import ai.kilocode.rpc.dto.DiffFileDto +import ai.kilocode.rpc.dto.GhAvailability +import ai.kilocode.rpc.dto.MoveStage +import com.intellij.ide.ActivityTracker +import com.intellij.openapi.actionSystem.ActionManager +import com.intellij.openapi.actionSystem.DataSink +import com.intellij.openapi.actionSystem.DefaultActionGroup +import com.intellij.openapi.actionSystem.UiDataProvider +import com.intellij.openapi.application.ApplicationManager +import com.intellij.util.concurrency.annotations.RequiresEdt +import com.intellij.util.ui.JBUI +import com.intellij.util.ui.components.BorderLayoutPanel +import java.awt.Color +import java.awt.Dimension + +/** + * Branch/PR dock shown above the prompt in the chat side panel. + * + * Two mutually exclusive layouts, stacked so the row height stays stable: + * - PR present: the shared [PrHeaderView] (state badge + PR title + changes badge). + * - No PR: a horizontally centered row with the New Worktree / Move to Worktree toolbar actions and + * the changes badge. + * + * The two actions are registered platform actions (`Kilo.Chat.NewWorktree`, `Kilo.Chat.MoveToWorktree`) + * rendered through an [com.intellij.openapi.actionSystem.ActionToolbar]; each is invisible when it is + * not enabled, so the dock never shows a lone action. The dock exposes its state to those actions via + * [ChatDockKeys.DOCK]. Collapses to nothing unless it has a PR, changes, or an enabled action. + */ +internal class BranchDock( + openDiff: () -> Unit, + private val onMove: () -> Unit, + private val onNewWorktree: (() -> Unit)? = null, +) : BorderLayoutPanel(), SessionEditorStyleTarget, UiDataProvider { + private val core = PrHeaderView(openDiff) + private val changes = BranchChangesBadge(openDiff) + private val group = DefaultActionGroup().apply { + ActionManager.getInstance().getAction("Kilo.Chat.NewWorktree")?.let { add(it) } + ActionManager.getInstance().getAction("Kilo.Chat.MoveToWorktree")?.let { add(it) } + } + private val toolbar = ActionManager.getInstance().createActionToolbar(PLACE, group, true) + private val actionRow = Stack.horizontal(UiStyle.Gap.sm()) + .next(toolbar.component) + .next(changes.align(HAlign.CENTER, VAlign.CENTER)) + .align(HAlign.CENTER, VAlign.CENTER) + private var files = emptyList() + private var branch: BranchStatusDto? = null + private var hasMessages = false + private var moving = false + private var stage: MoveStage? = null + + init { + isOpaque = true + toolbar.targetComponent = this + // Transparent so the toolbar shows the dock's prompt-matching background and tracks LaF. + toolbar.component.isOpaque = false + addToCenter(Stack.vertical().next(core).next(actionRow)) + isVisible = false + sync() + } + + override fun getBackground(): Color = SessionUiStyle.Colors.codeBlockBackground() + + override fun updateUI() { + super.updateUI() + border = JBUI.Borders.compound( + JBUI.Borders.customLineTop(JBUI.CurrentTheme.EditorTabs.borderColor()), + JBUI.Borders.empty(UiStyle.Gap.xs(), UiStyle.Gap.sm()), + ) + } + + override fun uiDataSnapshot(sink: DataSink) { + sink[ChatDockKeys.DOCK] = this + } + + @RequiresEdt + fun setChanges(files: List) { + this.files = files + sync() + } + + @RequiresEdt + fun setBranch(branch: BranchStatusDto?) { + this.branch = branch + sync() + } + + @RequiresEdt + fun setHasMessages(value: Boolean) { + if (hasMessages == value) return + hasMessages = value + sync() + } + + @RequiresEdt + fun setMoveProgress(stage: MoveStage, detail: String?) { + moving = stage != MoveStage.DONE && stage != MoveStage.ERROR + this.stage = if (moving) stage else null + sync() + } + + // ---- state read by the toolbar actions ---- + + fun newWorktreeEnabled(): Boolean = onNewWorktree != null && dockActive() && !moving + + fun moveEnabled(): Boolean = dockActive() && !moving + + fun moving(): Boolean = moving + + fun moveStage(): MoveStage? = stage + + fun changeCount(): Int = files.size + + fun triggerNewWorktree() = onNewWorktree?.invoke() ?: Unit + + fun triggerMove() = onMove() + + private fun dockActive(): Boolean = gitAvailable() && (hasMessages || files.isNotEmpty()) + + private fun gitAvailable(): Boolean { + val branch = branch ?: return false + return branch.availability != GhAvailability.GIT_MISSING + } + + private fun sync() { + val pull = branch?.pr + val count = files.size + core.update(count, files.sumOf { it.additions }, files.sumOf { it.deletions }, pull, branch?.branch.orEmpty()) + changes.update(count, files.sumOf { it.additions }, files.sumOf { it.deletions }) + + // PR present -> the informational PR header; otherwise the centered action row. + core.isVisible = pull != null + val rowVisible = pull == null && (dockActive() || moving) + actionRow.isVisible = rowVisible + + val next = pull != null || rowVisible + if (isVisible != next) isVisible = next + syncToolbar() + revalidate() + repaint() + } + + private fun syncToolbar() { + // Tests need a synchronous refresh to assert action presentations; production nudges the + // platform's action-update pass instead of the deprecated blocking updateActionsImmediately(). + if (ApplicationManager.getApplication().isUnitTestMode) { + @Suppress("DEPRECATION") + toolbar.updateActionsImmediately() + return + } + ActivityTracker.getInstance().inc() + } + + override fun getPreferredSize(): Dimension { + val base = super.getPreferredSize() + // Reserve a stable row height so the transcript does not jump as stats/PR arrive late. + return Dimension(base.width, maxOf(base.height, JBUI.scale(ROW_HEIGHT))) + } + + override fun getMinimumSize(): Dimension = preferredSize + + override fun getMaximumSize(): Dimension = Dimension(Int.MAX_VALUE, preferredSize.height) + + override fun applyStyle(style: SessionEditorStyle) { + core.applyStyle(style) + changes.applyStyle(style) + } + + private companion object { + const val ROW_HEIGHT = 34 + const val PLACE = "KiloChatBranchDock" + } +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/ChatDockKeys.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/ChatDockKeys.kt new file mode 100644 index 000000000000..bae860cebf7f --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/ChatDockKeys.kt @@ -0,0 +1,8 @@ +package ai.kilocode.client.session.ui.header + +import com.intellij.openapi.actionSystem.DataKey + +/** Exposes the chat [BranchDock] to the New Worktree / Move to Worktree toolbar actions. */ +internal object ChatDockKeys { + val DOCK: DataKey = DataKey.create("kilo.chat.branchDock") +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt new file mode 100644 index 000000000000..b570e35d3caa --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt @@ -0,0 +1,196 @@ +package ai.kilocode.client.session.ui.header + +import ai.kilocode.client.session.ui.style.SessionEditorStyle +import ai.kilocode.client.session.ui.style.SessionEditorStyleTarget +import ai.kilocode.client.ui.FilledBadgeIcon +import ai.kilocode.client.ui.UiStyle +import ai.kilocode.client.ui.layout.HAlign +import ai.kilocode.client.ui.layout.Stack +import ai.kilocode.client.ui.layout.VAlign +import ai.kilocode.client.ui.layout.align +import ai.kilocode.client.ui.prTooltip +import ai.kilocode.client.ui.stateLabel +import ai.kilocode.client.ui.style +import ai.kilocode.rpc.dto.GhState +import ai.kilocode.rpc.dto.WorktreePrDto +import ai.kilocode.rpc.dto.WorktreeStatsDto +import com.intellij.ide.BrowserUtil +import com.intellij.ui.SimpleColoredComponent +import com.intellij.ui.SimpleTextAttributes +import com.intellij.ui.components.JBLabel +import com.intellij.util.concurrency.annotations.RequiresEdt +import com.intellij.util.ui.JBUI +import com.intellij.util.ui.UIUtil +import com.intellij.util.ui.components.BorderLayoutPanel +import java.awt.Component +import java.awt.Cursor +import java.awt.event.MouseAdapter +import java.awt.event.MouseEvent + +/** + * Neutral core of the branch/PR header: a state badge (LEFT), the PR title (CENTER, click opens the + * PR in the browser), and a changes badge plus a host-fillable trailing action slot (RIGHT). + * + * Shared by the Agent Manager worktree editor ([ai.kilocode.client.agentManager.worktree.WorktreePrHeaderView]) + * and the chat [BranchDock]. Retained-mode: [update] mutates existing nodes rather than rebuilding. + * Stays non-opaque so the host owns background and borders. + */ +internal class PrHeaderView( + openDiff: () -> Unit, +) : BorderLayoutPanel(), SessionEditorStyleTarget { + private val status = JBLabel() + private val title = SimpleColoredComponent() + private val changes = BranchChangesBadge(openDiff) + private val statusPane = status.align(HAlign.LEFT, VAlign.CENTER) + private val actions = Stack.horizontal(UiStyle.Gap.sm()) + .next(changes.align(HAlign.CENTER, VAlign.CENTER)) + private var style = SessionEditorStyle.current() + private var pull: WorktreePrDto? = null + private var state: GhState? = null + private var number: String? = null + private var body: String? = null + private var tip: String? = null + private var url: String? = null + + init { + isOpaque = false + actions.isOpaque = false + actions.border = JBUI.Borders.emptyRight(UiStyle.Gap.sm()) + status.border = JBUI.Borders.empty(0, UiStyle.Gap.md(), 0, UiStyle.Gap.xs()) + title.border = JBUI.Borders.empty(0, UiStyle.Gap.sm()) + title.isOpaque = false + addToLeft(statusPane) + addToCenter(title) + addToRight(actions.align(HAlign.RIGHT, VAlign.CENTER)) + val listener = object : MouseAdapter() { + override fun mouseClicked(event: MouseEvent) { + url?.let(BrowserUtil::browse) + } + } + status.addMouseListener(listener) + title.addMouseListener(listener) + changes.applyStyle(style) + syncClick(null) + } + + /** Adds a host action into the trailing slot, to the right of the changes badge. */ + fun addAction(component: Component) { + actions.next(component.align(HAlign.CENTER, VAlign.CENTER)) + } + + /** Update from worktree branch stats (files/additions/deletions on the stats DTO). */ + @RequiresEdt + fun update(stats: WorktreeStatsDto?, pull: WorktreePrDto?, name: String) { + changes.update(stats?.files ?: 0, stats?.additions ?: 0, stats?.deletions ?: 0) + applyPr(pull, name) + } + + /** Update from precomputed change aggregates (chat dock aggregates a DiffFileDto list). */ + @RequiresEdt + fun update(files: Int, additions: Int, deletions: Int, pull: WorktreePrDto?, name: String) { + changes.update(files, additions, deletions) + applyPr(pull, name) + } + + @RequiresEdt + private fun applyPr(pull: WorktreePrDto?, name: String) { + this.pull = pull + if (pull == null) { + syncPr(false) + syncStatus(null) + clearTitle() + syncClick(null) + return + } + syncPr(true) + val trimmed = pull.title.trim() + val body = trimmed.takeIf { it.isNotBlank() } + val tip = prTooltip(pull, name.takeIf { it.isNotBlank() && it != trimmed }) + syncStatus(pull.state) + syncTitle("#${pull.number}", body, tip) + syncClick(pull.url) + status.toolTipText = tip + } + + private fun syncStatus(next: GhState?) { + if (state == next) { + val visible = next != null + if (status.isVisible != visible) status.isVisible = visible + return + } + state = next + status.icon = next?.let { FilledBadgeIcon(stateLabel(it), style(it)) } + status.isVisible = next != null + changed() + } + + private fun syncPr(value: Boolean) { + if (value) { + title.isVisible = true + return + } + title.isVisible = false + changed() + } + + private fun clearTitle() { + if (number == null && tip == null) return + number = null + body = null + tip = null + title.clear() + title.toolTipText = null + status.toolTipText = null + changed() + } + + private fun syncTitle(number: String, body: String?, nextTip: String?) { + var changed = false + if (this.number != number || this.body != body) { + this.number = number + this.body = body + renderTitle() + changed = true + } + if (tip != nextTip) { + tip = nextTip + title.toolTipText = nextTip + if (pull == null) status.toolTipText = null + changed = true + } + if (changed) changed() + } + + private fun renderTitle() { + val number = number ?: return + title.clear() + val body = body + if (body == null) { + title.append(number, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) + } else { + title.append(body, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) + title.append(" $number", SimpleTextAttributes.GRAYED_ATTRIBUTES) + } + } + + private fun syncClick(next: String?) { + if (url == next) return + url = next + val cursor = if (next != null) Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) else Cursor.getDefaultCursor() + status.cursor = cursor + title.cursor = cursor + } + + override fun applyStyle(style: SessionEditorStyle) { + this.style = style + changes.applyStyle(style) + // Re-render the title so its bold foreground follows the theme, then repaint. + renderTitle() + changed() + } + + private fun changed() { + revalidate() + repaint() + } +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/SessionHeaderPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/SessionHeaderPanel.kt index aed22219a944..8c2764dabbd1 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/SessionHeaderPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/SessionHeaderPanel.kt @@ -11,7 +11,6 @@ import ai.kilocode.client.session.views.todo.TodoListPanel import ai.kilocode.client.ui.HoverIcon import ai.kilocode.client.ui.UiStyle import ai.kilocode.client.ui.layout.Stack -import ai.kilocode.rpc.dto.DiffFileDto import ai.kilocode.rpc.dto.TodoDto import ai.kilocode.rpc.dto.TokensDto import com.intellij.icons.AllIcons @@ -43,7 +42,6 @@ class SessionHeaderPanel( private val controller: SessionController, parent: Disposable, private val readonly: Boolean = false, - onOpenBranchDiff: (() -> Unit)? = null, ) : BorderLayoutPanel(), SessionEditorStyleTarget { companion object { @@ -77,7 +75,6 @@ class SessionHeaderPanel( accessibleContext.accessibleName = KiloBundle.message("session.header.compact") addActionListener { controller.compact() } } - private val changes = BranchChangesBadge { onOpenBranchDiff?.invoke() } private val expand = JBLabel().apply { border = JBUI.Borders.empty(0, UiStyle.Gap.sm()) cursor = java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR) @@ -116,39 +113,6 @@ class SessionHeaderPanel( iconTextGap = UiStyle.Gap.xs() } private val top = BorderLayoutPanel() - // Lays the title out first with the branch-changes badge hugging its trailing edge, - // both vertically centered. The title ellipsizes so the badge stays visible on long titles. - private val centerGroup = object : JPanel(null) { - override fun getPreferredSize(): Dimension { - val ins = insets - val t = title.preferredSize - var w = t.width - var h = t.height - if (changes.isVisible) { - val b = changes.preferredSize - w += UiStyle.Gap.sm() + b.width - h = maxOf(h, b.height) - } - return Dimension(w + ins.left + ins.right, h + ins.top + ins.bottom) - } - - override fun doLayout() { - val ins = insets - val availW = maxOf(0, width - ins.left - ins.right) - val availH = maxOf(0, height - ins.top - ins.bottom) - val t = title.preferredSize - val gap = if (changes.isVisible) UiStyle.Gap.sm() else 0 - val b = if (changes.isVisible) changes.preferredSize else Dimension(0, 0) - val badgeW = minOf(b.width, availW) - val titleW = minOf(t.width, maxOf(0, availW - badgeW - gap)) - val titleH = minOf(t.height, availH) - title.setBounds(ins.left, ins.top + (availH - titleH) / 2, titleW, titleH) - if (changes.isVisible) { - val badgeH = minOf(b.height, availH) - changes.setBounds(ins.left + titleW + gap, ins.top + (availH - badgeH) / 2, badgeW, badgeH) - } - } - } private val right = Stack.horizontal() .next(cost) .gap(UiStyle.Gap.xl()) @@ -203,10 +167,8 @@ class SessionHeaderPanel( isOpaque = true updateUI() - centerGroup.add(title) - centerGroup.add(changes) top.add(expand, BorderLayout.WEST) - top.add(centerGroup, BorderLayout.CENTER) + top.add(title, BorderLayout.CENTER) top.add(right, BorderLayout.EAST) add(top, BorderLayout.NORTH) timeline.addMouseListener(object : MouseAdapter() { @@ -307,17 +269,6 @@ class SessionHeaderPanel( refresh() } - fun setBranchChanges(files: List) { - if (!changes.update(files)) return - refresh() - } - - fun hideBranchChanges() { - if (!changes.isVisible) return - changes.isVisible = false - refresh() - } - override fun applyStyle(style: SessionEditorStyle) { this.style = style val bg = SessionUiStyle.Colors.sessionBackground() @@ -326,10 +277,7 @@ class SessionHeaderPanel( top.background = bg top.isOpaque = true top.border = JBUI.Borders.empty(UiStyle.Gap.md(), UiStyle.Gap.sm(), UiStyle.Gap.md(), UiStyle.Gap.sm()) - centerGroup.background = bg - centerGroup.isOpaque = true right.background = bg - changes.background = bg tokens.background = bg todoRow.background = bg todoBox.background = bg @@ -337,7 +285,6 @@ class SessionHeaderPanel( viewport.background = bg title.font = style.boldFont title.foreground = style.editorForeground - changes.applyStyle(style) cost.font = style.regularFont cost.foreground = style.editorForeground cost.icon = null @@ -402,16 +349,6 @@ class SessionHeaderPanel( internal fun compactButton() = compact - internal fun changesBadge() = changes - - internal fun changesVisible() = changes.isVisible - - internal fun changesText() = changes.countText() - - internal fun changesStat() = changes.stats() - - internal fun centerGroupPanel() = centerGroup - internal fun rightPanel() = right internal fun expandButton() = expand diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/PrBadges.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/PrBadges.kt new file mode 100644 index 000000000000..5463772cb144 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/PrBadges.kt @@ -0,0 +1,45 @@ +package ai.kilocode.client.ui + +import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.rpc.dto.GhState +import ai.kilocode.rpc.dto.WorktreePrDto +import com.intellij.xml.util.XmlStringUtil + +/** + * Shared PR badge helpers used by both the Agent Manager worktree views and the chat session header. + * Lives in the neutral `ui` package so `session/ui/header/` does not depend on the Agent Manager + * package. + */ + +internal fun style(state: GhState): UiStyle.Badge.Style = when (state) { + GhState.OPEN -> UiStyle.Badge.PullRequestOpen + GhState.DRAFT -> UiStyle.Badge.PullRequestDraft + GhState.MERGED -> UiStyle.Badge.PullRequestMerged + GhState.CLOSED -> UiStyle.Badge.PullRequestClosed +} + +internal fun stateLabel(state: GhState): String = when (state) { + GhState.OPEN -> KiloBundle.message("worktree.pr.state.open") + GhState.DRAFT -> KiloBundle.message("worktree.pr.state.draft") + GhState.MERGED -> KiloBundle.message("worktree.pr.state.merged") + GhState.CLOSED -> KiloBundle.message("worktree.pr.state.closed") +} + +internal fun prTooltip(pull: WorktreePrDto, name: String? = null): String { + val title = pull.title.trim() + val head = buildString { + append(stateLabel(pull.state)) + append(" #") + append(pull.number) + if (title.isNotBlank()) { + append(' ') + append(title) + } + } + val lines = listOfNotNull( + head, + name?.takeIf { title.isNotBlank() }?.let { "($it)" }, + KiloBundle.message("worktree.pr.tooltip.open"), + ).map(XmlStringUtil::escapeString) + return XmlStringUtil.wrapInHtml(lines.joinToString("
")) +} diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/kilo.jetbrains.frontend.xml b/packages/kilo-jetbrains/frontend/src/main/resources/kilo.jetbrains.frontend.xml index aeecfb90e2b3..56521dbdf513 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/kilo.jetbrains.frontend.xml +++ b/packages/kilo-jetbrains/frontend/src/main/resources/kilo.jetbrains.frontend.xml @@ -208,6 +208,16 @@ + + + + diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties index 7d759a738d3e..6b0f7e387345 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties @@ -139,6 +139,17 @@ session.part.compaction=context compacted session.changes.modified=Modified session.changes.count.one={0} file session.changes.count.other={0} files +session.dock.newWorktree=New Worktree +session.dock.newWorktree.tooltip=Create a new git worktree with its own branch and session. +session.dock.move=Move to Worktree +session.dock.move.tooltip.empty=Move this conversation and your current local changes into a dedicated worktree for isolated follow-up work. +session.dock.move.tooltip.one=Move this conversation and 1 changed file into a dedicated worktree for isolated follow-up work. +session.dock.move.tooltip.other=Move this conversation and {0} changed files into a dedicated worktree for isolated follow-up work. +session.dock.progress.capturing=Capturing changes... +session.dock.progress.creating=Creating worktree... +session.dock.progress.transferring=Transferring changes... +session.dock.progress.forking=Starting session... +session.dock.move.failed.title=Failed to move to worktree diff.editor.session.title=Session Changes diff.editor.inline.title.named={0} ({1}) diff.editor.changedFiles.title=Changed files diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt index 96e0f2572caf..099c38b19e22 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt @@ -3,6 +3,8 @@ package ai.kilocode.client.agentManager.worktree import ai.kilocode.client.session.ui.header.BranchChangesBadge import ai.kilocode.client.ui.FilledBadgeIcon import ai.kilocode.client.ui.HoverIcon +import ai.kilocode.client.ui.stateLabel +import ai.kilocode.client.ui.style import ai.kilocode.client.util.edtWait import ai.kilocode.rpc.dto.GhState import ai.kilocode.rpc.dto.WorktreePrDto diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt index 55f07883155e..13d871fe57c2 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt @@ -19,6 +19,7 @@ import ai.kilocode.client.session.ui.SessionMessageListPanel import ai.kilocode.client.session.ui.SessionRootPanel import ai.kilocode.client.session.ui.SessionView import ai.kilocode.client.session.ui.style.SessionEditorStyle +import ai.kilocode.client.session.ui.header.BranchDock import ai.kilocode.client.session.ui.header.SessionHeaderPanel import ai.kilocode.client.session.ui.style.SessionUiStyle import ai.kilocode.client.session.controller.SessionControllerEvent @@ -82,13 +83,51 @@ class SessionUiLayoutTest : SessionUiTestBase() { val connection = find(ui) val prompt = find(ui) + // Prompt sits inside an Align inside the bottom Stack container, which is docked SOUTH. assertTrue(prompt.parent is Align) - assertSame(root.content, prompt.parent.parent) + assertSame(root.content, prompt.parent.parent.parent) assertSame(root.overlay, connection.parent) assertTrue(root.overlay.components.any { it is SessionAccountOverlay }) assertFalse(root.content.components.contains(connection)) } + fun `test dock is docked between scroll pane and prompt`() { + val prompt = find(ui) + val dock = find(ui) + + // Dock and the aligned prompt share the bottom container; the dock comes first (above prompt). + val container = dock.parent + assertSame(container, prompt.parent.parent) + assertTrue(container.getComponentZOrder(dock) < container.getComponentZOrder(prompt.parent)) + } + + fun `test readonly session omits dock`() { + val owner = object : SessionManager { + override fun newSession() {} + override fun showHistory(back: (() -> Unit)?) {} + override fun openSession(ref: SessionRef) {} + override val readonly: Boolean get() = true + } + rpc.history.addAll(history(1)) + ui = newUi(id = "ses_test", manager = owner) + settle() + + assertNull(find(ui, BranchDock::class.java)) + } + + fun `test dock absent when manager disables branch dock`() { + val owner = object : SessionManager { + override fun newSession() {} + override fun showHistory(back: (() -> Unit)?) {} + override fun openSession(ref: SessionRef) {} + override val showsBranchDock: Boolean get() = false + } + ui = newUi(manager = owner) + settle() + + assertNull(find(ui, BranchDock::class.java)) + } + fun `test transcript uses larger standard gap before prompts after first item`() { val panel = SessionLayoutPanel(gap = SessionUiStyle.SessionLayout.GAP).apply { setSize(400, 300) @@ -123,16 +162,16 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertNull(drop.dropTarget) } - fun `test branch changes badge refreshes on finish and revert`() { + fun `test dock branch changes refresh on finish and revert`() { workspaceRpc.branchDiffs.clear() workspaceRpc.branchDiffs.add(DiffFileDto("src/A.kt", 2, 1)) - val header = find(ui) + val badge = find(ui) controller().model.setState(SessionState.Busy("running")) controller().model.setState(SessionState.Idle) settle() - assertEquals(2 to 1, header.changesStat()) + assertEquals(2 to 1, badge.stats()) workspaceRpc.branchDiffs.clear() workspaceRpc.branchDiffs.add(DiffFileDto("src/B.kt", 4, 3)) @@ -140,14 +179,14 @@ class SessionUiLayoutTest : SessionUiTestBase() { controller().model.setState(SessionState.Idle) settle() - assertEquals(4 to 3, header.changesStat()) + assertEquals(4 to 3, badge.stats()) workspaceRpc.branchDiffs.clear() workspaceRpc.branchDiffs.add(DiffFileDto("src/C.kt", 1, 0)) controller().model.setRevert(SessionRevertDto("msg1", "part1", diff = "patch")) settle() - assertEquals(1 to 0, header.changesStat()) + assertEquals(1 to 0, badge.stats()) } fun `test prompt file drag leave does not immediately hide drop overlay`() { @@ -275,7 +314,7 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertSame(root.overlay, connection.parent) assertEquals(point.x + gap, connection.x) assertEquals(prompt.width - gap * 2, connection.width) - assertEquals(point.y - gap, connection.y + connection.height) + assertEquals(bottomTop(root, prompt) - gap, connection.y + connection.height) } fun `test expanded connection panel remains anchored above prompt`() { @@ -292,7 +331,7 @@ class SessionUiLayoutTest : SessionUiTestBase() { layout() assertTrue(connection.detailsVisible()) - assertEquals(promptPoint(root, prompt).y - SessionUiStyle.View.contentGap(), connection.y + connection.height) + assertEquals(bottomTop(root, prompt) - SessionUiStyle.View.contentGap(), connection.y + connection.height) } fun `test expanded connection panel is capped to transcript height`() { @@ -314,7 +353,7 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertTrue(connection.detailsVisible()) assertEquals(0, connection.y) - assertEquals(promptPoint(root, prompt).y - SessionUiStyle.View.contentGap(), connection.y + connection.height) + assertEquals(bottomTop(root, prompt) - SessionUiStyle.View.contentGap(), connection.y + connection.height) assertTrue(pane.viewport.extentSize.height < pane.viewport.view.preferredSize.height) } @@ -335,7 +374,7 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertTrue(find(ui).isVisible) assertSame(find(ui), find(ui).parent) assertEquals(top, connection.y) - assertEquals(promptPoint(root, prompt).y - SessionUiStyle.View.contentGap(), connection.y + connection.height) + assertEquals(bottomTop(root, prompt) - SessionUiStyle.View.contentGap(), connection.y + connection.height) assertSame(find(ui), scrollView()) } @@ -356,7 +395,7 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertTrue(find(ui).isVisible) assertSame(find(ui), find(ui).parent) assertEquals(top, connection.y) - assertEquals(promptPoint(root, prompt).y - SessionUiStyle.View.contentGap(), connection.y + connection.height) + assertEquals(bottomTop(root, prompt) - SessionUiStyle.View.contentGap(), connection.y + connection.height) assertSame(find(ui), scrollView()) } @@ -826,6 +865,13 @@ class SessionUiLayoutTest : SessionUiTestBase() { private fun promptPoint(root: SessionRootPanel, prompt: PromptPanel) = SwingUtilities.convertPoint(prompt.parent, prompt.x, prompt.y, root.overlay) + // Top of the bottom container (branch dock + prompt) in overlay coordinates. The connection + // banner anchors above this so it floats over the dock rather than covering it. + private fun bottomTop(root: SessionRootPanel, prompt: PromptPanel): Int { + val container = prompt.parent.parent + return SwingUtilities.convertPoint(container.parent, container.x, container.y, root.overlay).y + } + private fun layoutReadonly() { ui.doLayout() val root = find(ui) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiTestBase.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiTestBase.kt index 62375f8bc80f..33025c223da6 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiTestBase.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiTestBase.kt @@ -115,6 +115,9 @@ abstract class SessionUiTestBase : BasePlatformTestCase() { val root = find(ui) root.doLayout() root.content.doLayout() + // The prompt sits inside an Align inside the bottom Stack container (which also holds the + // branch dock). Lay out the Stack before the Align so the prompt receives its full width. + find(ui).parent.parent.doLayout() find(ui).parent.doLayout() scrollComponent().doLayout() (scrollView() as? Container)?.doLayout() diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/subagent/SubagentSessionEditorHostTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/subagent/SubagentSessionEditorHostTest.kt index 4fcf03c82e78..d3887372b266 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/subagent/SubagentSessionEditorHostTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/subagent/SubagentSessionEditorHostTest.kt @@ -37,7 +37,7 @@ class SubagentSessionEditorHostTest : BasePlatformTestCase() { assertTrue(host.readonly) assertTrue(host.hostedInEditorTab) - assertFalse(host.showsBranchBadgeInHeader) + assertFalse(host.showsBranchDock) } fun testOpenPresentsSessionUi() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt new file mode 100644 index 000000000000..5f82ec61c4aa --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt @@ -0,0 +1,195 @@ +package ai.kilocode.client.session.ui.header + +import ai.kilocode.client.actions.ChatMoveToWorktreeAction +import ai.kilocode.client.actions.ChatNewWorktreeAction +import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.util.edtWait +import ai.kilocode.rpc.dto.BranchStatusDto +import ai.kilocode.rpc.dto.DiffFileDto +import ai.kilocode.rpc.dto.GhAvailability +import ai.kilocode.rpc.dto.GhState +import ai.kilocode.rpc.dto.MoveStage +import ai.kilocode.rpc.dto.WorktreePrDto +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.DataContext +import com.intellij.openapi.actionSystem.Presentation +import com.intellij.openapi.actionSystem.ex.ActionUtil +import com.intellij.testFramework.fixtures.BasePlatformTestCase + +@Suppress("UnstableApiUsage") +class BranchDockTest : BasePlatformTestCase() { + + // ---- dock visibility ---- + + fun `test dock visible with messages`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + } + assertTrue(edt { dock.isVisible }) + } + + fun `test dock visible with changes`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = true, availability = GhAvailability.OK)) + dock.setChanges(listOf(DiffFileDto("src/A.kt", 2, 1))) + } + assertTrue(edt { dock.isVisible }) + } + + fun `test dock hidden with nothing to show`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "main", worktree = false, availability = GhAvailability.OK)) + } + assertFalse(edt { dock.isVisible }) + } + + fun `test dock hidden when git missing`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "main", worktree = false, availability = GhAvailability.GIT_MISSING)) + dock.setHasMessages(true) + } + assertFalse(edt { dock.isVisible }) + } + + fun `test PR makes dock visible`() { + val dock = dock() + edt { + dock.setBranch( + BranchStatusDto( + branch = "feature-x", + worktree = true, + availability = GhAvailability.GIT_MISSING, + pr = WorktreePrDto("/repo", 7, GhState.OPEN, "https://pr/7", "Title"), + ), + ) + } + assertTrue(edt { dock.isVisible }) + } + + // ---- Move to Worktree action ---- + + fun `test move action visible with messages`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + } + val p = update(ChatMoveToWorktreeAction(), dock) + assertTrue(p.isVisible) + assertTrue(p.isEnabled) + assertEquals(KiloBundle.message("session.dock.move"), p.text) + } + + fun `test move action visible with changes and no messages`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setChanges(listOf(DiffFileDto("src/A.kt", 2, 1))) + } + assertTrue(update(ChatMoveToWorktreeAction(), dock).isVisible) + } + + fun `test move action hidden with nothing to move`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + } + assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) + } + + fun `test move action hidden when git missing`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.GIT_MISSING)) + dock.setHasMessages(true) + } + assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) + } + + fun `test move action shows spinner while moving`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + dock.setMoveProgress(MoveStage.CREATING, null) + } + val p = update(ChatMoveToWorktreeAction(), dock) + assertTrue(p.isVisible) + assertFalse(p.isEnabled) + assertEquals(KiloBundle.message("session.dock.progress.creating"), p.text) + } + + fun `test move action invokes callback`() { + var moved = 0 + val dock = edt { BranchDock(openDiff = {}, onMove = { moved++ }) } + val action = ChatMoveToWorktreeAction() + val event = event(action, dock) + edt { ActionUtil.updateAction(action, event) } + edt { action.actionPerformed(event) } + assertEquals(1, moved) + } + + // ---- New Worktree action ---- + + fun `test new worktree action visible when dock active`() { + val dock = dockWithNewWorktree() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + } + val p = update(ChatNewWorktreeAction(), dock) + assertTrue(p.isVisible) + assertEquals(KiloBundle.message("session.dock.newWorktree"), p.text) + } + + fun `test new worktree action hidden with nothing to show`() { + val dock = dockWithNewWorktree() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + } + assertFalse(update(ChatNewWorktreeAction(), dock).isVisible) + } + + fun `test new worktree action hidden without callback`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + } + assertFalse(update(ChatNewWorktreeAction(), dock).isVisible) + } + + fun `test new worktree action invokes callback`() { + var fired = 0 + val dock = edt { BranchDock(openDiff = {}, onMove = {}, onNewWorktree = { fired++ }) } + val action = ChatNewWorktreeAction() + val event = event(action, dock) + edt { ActionUtil.updateAction(action, event) } + edt { action.actionPerformed(event) } + assertEquals(1, fired) + } + + private fun dock(): BranchDock = edt { BranchDock(openDiff = {}, onMove = {}) } + + private fun dockWithNewWorktree(): BranchDock = edt { BranchDock(openDiff = {}, onMove = {}, onNewWorktree = {}) } + + private fun update(action: AnAction, dock: BranchDock): Presentation { + val event = event(action, dock) + edt { ActionUtil.updateAction(action, event) } + return event.presentation + } + + private fun event(action: AnAction, dock: BranchDock): AnActionEvent { + val presentation = Presentation().apply { copyFrom(action.templatePresentation) } + val context = DataContext { id -> if (ChatDockKeys.DOCK.`is`(id)) dock else null } + return AnActionEvent.createFromDataContext("", presentation, context) + } + + private fun edt(block: () -> T): T = edtWait(block) +} diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt new file mode 100644 index 000000000000..1743071d0e46 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt @@ -0,0 +1,126 @@ +package ai.kilocode.client.session.ui.header + +import ai.kilocode.client.session.ui.style.SessionEditorStyle +import ai.kilocode.client.ui.FilledBadgeIcon +import ai.kilocode.client.ui.stateLabel +import ai.kilocode.client.ui.style +import ai.kilocode.client.util.edtWait +import ai.kilocode.rpc.dto.GhState +import ai.kilocode.rpc.dto.WorktreePrDto +import ai.kilocode.rpc.dto.WorktreeStatsDto +import com.intellij.testFramework.fixtures.BasePlatformTestCase +import com.intellij.ui.SimpleColoredComponent +import com.intellij.ui.components.JBLabel +import com.intellij.util.ui.UIUtil +import java.awt.Component +import java.awt.Container +import java.awt.Cursor +import javax.swing.JButton + +class PrHeaderViewTest : BasePlatformTestCase() { + fun `test PR renders state badge title and link`() { + val view = edt { PrHeaderView {} } + + edt { view.update(files = 0, additions = 0, deletions = 0, pull = pull(GhState.OPEN), name = "feature-x") } + + val badge = edt { badge(view) } + val title = edt { title(view) } + assertEquals(stateLabel(GhState.OPEN), (badge.icon as FilledBadgeIcon).text) + assertSame(style(GhState.OPEN), (badge.icon as FilledBadgeIcon).style) + assertEquals(listOf("Implement header", " #123"), edt { fragments(title) }) + assertEquals(Cursor.HAND_CURSOR, edt { title.cursor.type }) + } + + fun `test no PR hides badge and title`() { + val view = edt { PrHeaderView {} } + + edt { view.update(files = 0, additions = 0, deletions = 0, pull = null, name = "feature-x") } + + assertNull(edt { components(view).filterIsInstance().firstOrNull { it.icon is FilledBadgeIcon } }) + assertFalse(edt { title(view).isVisible }) + } + + fun `test changes aggregate from stats overload`() { + val view = edt { PrHeaderView {} } + val changes = edt { UIUtil.findComponentOfType(view, BranchChangesBadge::class.java)!! } + + edt { view.update(WorktreeStatsDto("/repo", additions = 7, deletions = 4, files = 3), null, "feature-x") } + + assertEquals("3 files", edt { changes.countText() }) + assertEquals(7 to 4, edt { changes.stats() }) + assertTrue(edt { changes.isVisible }) + } + + fun `test action slot adds trailing control`() { + val view = edt { PrHeaderView {} } + val button = edt { JButton("Move").also { view.addAction(it) } } + + assertTrue(edt { components(view).contains(button) }) + } + + fun `test repeated update keeps child instances and bounded count`() { + val view = edt { PrHeaderView {} } + val stats = WorktreeStatsDto("/repo", additions = 2, files = 1) + val pull = pull(GhState.DRAFT) + + edt { view.update(stats, pull, "feature-x") } + val labels = edt { components(view).filterIsInstance() } + val title = edt { title(view) } + val changes = edt { UIUtil.findComponentOfType(view, BranchChangesBadge::class.java)!! } + val count = edt { components(view).size } + + repeat(20) { edt { view.update(stats, pull, "feature-x") } } + + assertEquals(labels, edt { components(view).filterIsInstance() }) + assertSame(title, edt { title(view) }) + assertSame(changes, edt { UIUtil.findComponentOfType(view, BranchChangesBadge::class.java) }) + assertEquals(count, edt { components(view).size }) + } + + fun `test applyStyle refreshes title without rebuilding`() { + val view = edt { PrHeaderView {} } + edt { view.update(files = 1, additions = 1, deletions = 0, pull = pull(GhState.OPEN), name = "feature-x") } + val title = edt { title(view) } + + edt { view.applyStyle(SessionEditorStyle.current()) } + + assertSame(title, edt { title(view) }) + assertEquals(listOf("Implement header", " #123"), edt { fragments(title) }) + } + + private fun pull(state: GhState) = WorktreePrDto( + path = "/repo", + number = 123, + state = state, + url = "https://github.com/kilo/test/pull/123", + title = "Implement header", + ) + + private fun badge(view: PrHeaderView): JBLabel = + components(view).filterIsInstance().single { it.icon is FilledBadgeIcon } + + private fun title(view: PrHeaderView): SimpleColoredComponent = + components(view).filterIsInstance().single() + + private fun fragments(title: SimpleColoredComponent): List { + val out = mutableListOf() + val iter = title.iterator() + while (iter.hasNext()) { + iter.next() + out += iter.fragment + } + return out + } + + private fun components(root: Component): List { + val out = mutableListOf() + fun visit(item: Component) { + out += item + if (item is Container) item.components.forEach { visit(it) } + } + visit(root) + return out + } + + private fun edt(block: () -> T): T = edtWait(block) +} diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/SessionHeaderPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/SessionHeaderPanelTest.kt index f68b703234fb..9e5ba5fa3ce7 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/SessionHeaderPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/SessionHeaderPanelTest.kt @@ -126,70 +126,6 @@ class SessionHeaderPanelTest : SessionControllerTestBase() { assertEquals(1, rpc.compacts.size) } - fun `test branch changes badge shows count stats and hides when empty`() { - val c = promptedHeader() - val panel = SessionHeaderPanel(c, parent) - - assertFalse(panel.changesVisible()) - - panel.setBranchChanges(listOf( - DiffFileDto("src/A.kt", 2, 1), - DiffFileDto("src/B.kt", 0, 3), - DiffFileDto("src/C.kt", 5, 0), - )) - - assertTrue(panel.changesVisible()) - assertEquals("3 files", panel.changesText()) - assertEquals(7 to 4, panel.changesStat()) - - panel.setBranchChanges(emptyList()) - - assertFalse(panel.changesVisible()) - } - - fun `test branch changes badge invokes callback when clicked`() { - val c = promptedHeader() - var opened = 0 - val panel = SessionHeaderPanel(c, parent) { opened++ } - val badge = panel.changesBadge() - - panel.setBranchChanges(listOf(DiffFileDto("src/A.kt", 2, 1))) - - assertTrue(badge.isVisible) - assertEquals(KiloBundle.message("diff.editor.branch.tooltip"), badge.toolTipText) - assertEquals(KiloBundle.message("diff.editor.branch.tooltip"), badge.accessibleContext.accessibleName) - - click(badge) - - assertEquals(1, opened) - } - - fun `test branch changes badge is hidden without files even with callback`() { - val c = promptedHeader() - val panel = SessionHeaderPanel(c, parent) {} - - assertFalse(panel.changesVisible()) - } - - fun `test branch changes badge no-op update does not repaint`() { - val c = promptedHeader() - val panel = SessionHeaderPanel(c, parent) - val files = listOf(DiffFileDto("src/A.kt", 2, 1)) - panel.setBranchChanges(files) - val prev = RepaintManager.currentManager(panel) - val tracker = TrackingRepaintManager(panel.changesBadge()) - - try { - RepaintManager.setCurrentManager(tracker) - panel.setBranchChanges(files) - - assertTrue(tracker.dirty.isEmpty()) - assertTrue(tracker.invalid.isEmpty()) - } finally { - RepaintManager.setCurrentManager(prev) - } - } - fun `test clicking session title toggles expansion`() { val c = promptedHeader() val panel = SessionHeaderPanel(c, parent) @@ -203,16 +139,15 @@ class SessionHeaderPanelTest : SessionControllerTestBase() { assertFalse(panel.isExpanded()) } - fun `test top row places expand center group and right controls`() { + fun `test top row places expand title and right controls`() { val c = promptedHeader() val panel = SessionHeaderPanel(c, parent) val top = panel.expandButton().parent val layout = top.layout as java.awt.BorderLayout assertSame(panel.expandButton(), layout.getLayoutComponent(java.awt.BorderLayout.WEST)) - assertSame(panel.centerGroupPanel(), layout.getLayoutComponent(java.awt.BorderLayout.CENTER)) + assertSame(panel.titleLabel(), layout.getLayoutComponent(java.awt.BorderLayout.CENTER)) assertSame(panel.rightPanel(), layout.getLayoutComponent(java.awt.BorderLayout.EAST)) - assertSame(panel.centerGroupPanel(), panel.changesBadge().parent) assertSame(panel.rightPanel(), panel.compactButton().parent) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt index 697ff0fbd33c..b4fd679f5213 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt @@ -1,9 +1,11 @@ package ai.kilocode.client.testing import ai.kilocode.rpc.KiloWorktreeRpcApi +import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.CreateWorktreeRequestDto import ai.kilocode.rpc.dto.CreateWorktreeResultDto import ai.kilocode.rpc.dto.GhAvailability +import ai.kilocode.rpc.dto.MoveProgressDto import ai.kilocode.rpc.dto.RemoveWorktreeResultDto import ai.kilocode.rpc.dto.RenameWorktreeResultDto import ai.kilocode.rpc.dto.WorktreeBranchesDto @@ -11,6 +13,8 @@ import ai.kilocode.rpc.dto.WorktreeDto import ai.kilocode.rpc.dto.WorktreeListDto import ai.kilocode.rpc.dto.WorktreePrListDto import ai.kilocode.rpc.dto.WorktreeStatsListDto +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.asFlow import java.util.concurrent.CopyOnWriteArrayList /** @@ -23,7 +27,11 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { var statsResult = WorktreeStatsListDto() var ghResult = GhAvailability.OK var prResult = WorktreePrListDto() + var branchResult = BranchStatusDto() var currentBranch: String? = null + val moves = CopyOnWriteArrayList>() + /** Progress events emitted by [moveToWorktree], in order. */ + var moveScript: List = emptyList() val creates = CopyOnWriteArrayList() val removes = CopyOnWriteArrayList>() val removeForces = CopyOnWriteArrayList() @@ -85,6 +93,17 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { return prResult } + override suspend fun branchStatus(directory: String): BranchStatusDto { + assertNotEdt("branchStatus") + return branchResult + } + + override suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow { + assertNotEdt("moveToWorktree") + moves.add(Triple(directory, sessionId, branch)) + return moveScript.asFlow() + } + override suspend fun open(directory: String): Boolean { assertNotEdt("open") opens.add(directory) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt index c8ea4f031e44..e2014a5f3202 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt @@ -1,6 +1,5 @@ package ai.kilocode.client.ui -import ai.kilocode.client.agentManager.worktree.style import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.client.session.ui.style.SessionUiStyle import ai.kilocode.rpc.dto.GhState diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt index 5c0a4dbba8fe..0db24c99d448 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt @@ -1,8 +1,10 @@ package ai.kilocode.rpc +import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.CreateWorktreeRequestDto import ai.kilocode.rpc.dto.CreateWorktreeResultDto import ai.kilocode.rpc.dto.GhAvailability +import ai.kilocode.rpc.dto.MoveProgressDto import ai.kilocode.rpc.dto.RemoveWorktreeResultDto import ai.kilocode.rpc.dto.RenameWorktreeResultDto import ai.kilocode.rpc.dto.WorktreeBranchesDto @@ -13,6 +15,7 @@ import com.intellij.platform.rpc.RemoteApiProviderService import fleet.rpc.RemoteApi import fleet.rpc.Rpc import fleet.rpc.remoteApiDescriptor +import kotlinx.coroutines.flow.Flow /** * Git-worktree RPC API exposed from backend to frontend. @@ -40,6 +43,20 @@ interface KiloWorktreeRpcApi : RemoteApi { suspend fun stats(directory: String): WorktreeStatsListDto suspend fun ghStatus(directory: String): GhAvailability suspend fun prStatus(directory: String): WorktreePrListDto + + /** + * Single-directory branch status for the chat branch/PR dock: current branch, worktree flag, + * gh availability, and the PR for the branch (if any). Cached with the same TTL as [prStatus]. + */ + suspend fun branchStatus(directory: String): BranchStatusDto + + /** + * Moves the session [sessionId] running in [directory] into a fresh worktree on [branch]: + * captures uncommitted changes, creates the worktree at the source HEAD, transfers the changes, + * then forks the session into it. Emits one [MoveProgressDto] per stage; [branch] is generated + * on the frontend from the known branch list. + */ + suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow suspend fun listBranches(directory: String): WorktreeBranchesDto suspend fun create(directory: String, request: CreateWorktreeRequestDto): CreateWorktreeResultDto diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt index e88fb5db3032..848817f307a7 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt @@ -50,6 +50,32 @@ data class WorktreePrListDto( val items: List = emptyList(), ) +/** + * Single-directory branch status for the chat branch/PR dock: the current branch, whether the + * directory is a linked worktree, gh availability, and the PR for the branch (if any). + */ +@Serializable +data class BranchStatusDto( + val branch: String = "", + val worktree: Boolean = false, + val availability: GhAvailability = GhAvailability.OK, + val pr: WorktreePrDto? = null, +) + +/** Stages of the "Move to Worktree" flow. Mirrors VS Code's ContinueInWorktreeStatus minus setup. */ +@Serializable +enum class MoveStage { CAPTURING, CREATING, TRANSFERRING, FORKING, DONE, ERROR } + +/** Progress event streamed while moving a session into a new worktree. */ +@Serializable +data class MoveProgressDto( + val stage: MoveStage, + val detail: String? = null, + val error: String? = null, + val worktree: WorktreeDto? = null, + val session: String? = null, +) + @Serializable data class WorktreeBranchesDto( val branches: List = emptyList(), From 32573a0a1d94c4369ce5ee8a69b9e11c1cbf5e8d Mon Sep 17 00:00:00 2001 From: kirillk Date: Sun, 23 Aug 2026 23:16:05 -0400 Subject: [PATCH 21/30] fix(jetbrains): show chat worktree actions only while the session is idle New Worktree and Move to Worktree were offered mid-turn, where neither is a sensible thing to invoke: the move aborts the session and forks it, and both compete with a running agent. The dock's action row now withdraws while the session is active (any busy state, including a pending permission or question), matching the VS Code sidebar dock. A move in progress keeps the row so its spinner and stage stay visible, and the PR row is unaffected because it is informational rather than an action. The dock sits outside the scroll pane, so releasing its row resizes the transcript viewport twice per turn instead of once per session. SessionScroll already re-pins from its viewport listener, but followTail() routed the not-following case through followBottom(false), which bumped the generation counter and aborted in-flight multi-pass chains on the first streamed content growth. It now re-pins only when already following and otherwise just refreshes the jump button, which is what onViewport wanted all along. The connection-panel layout tests compared an absolute connection.y across a state change, encoding an assumption that the bottom container never changes height. They now assert the actual invariant: the banner stays one content gap above that container. --- .changeset/jetbrains-dock-idle-actions.md | 5 + .../ai/kilocode/client/session/SessionUi.kt | 1 + .../client/session/scroll/SessionScroll.kt | 21 ++- .../client/session/ui/header/BranchDock.kt | 13 +- .../client/session/SessionScrollTest.kt | 158 ++++++++++++++++++ .../client/session/SessionUiLayoutTest.kt | 38 ++++- .../session/ui/header/BranchDockTest.kt | 79 +++++++++ 7 files changed, 305 insertions(+), 10 deletions(-) create mode 100644 .changeset/jetbrains-dock-idle-actions.md diff --git a/.changeset/jetbrains-dock-idle-actions.md b/.changeset/jetbrains-dock-idle-actions.md new file mode 100644 index 000000000000..73b2633652f6 --- /dev/null +++ b/.changeset/jetbrains-dock-idle-actions.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Show the chat New Worktree and Move to Worktree actions only while the session is idle, and keep the transcript pinned to the newest message when that row appears or disappears. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt index edb1ce251db6..cdb6c724db00 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt @@ -1108,6 +1108,7 @@ class SessionUi( pendingRedo = null } prompt.setBusy(busy) + dock?.setBusy(busy) load.setState(state) scroll.setQuestionPending(questionPending(state)) scroll.show(body(state)) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/scroll/SessionScroll.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/scroll/SessionScroll.kt index 012182dd653c..6279bdd6e004 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/scroll/SessionScroll.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/scroll/SessionScroll.kt @@ -140,9 +140,23 @@ internal class SessionScroll( } } + /** + * Re-pins the bottom, but only when the transcript is already following it. Call this after + * anything that will resize the viewport or the content (transcript reflow, the branch dock + * taking or releasing its row above the prompt): it clears a pending user-gesture flag before + * the relayout can be mistaken for a scroll away from the bottom. + * + * The not-following case deliberately only refreshes the jump button. Routing it through + * [followBottom] with `false` would bump the generation counter and abort in-flight multi-pass + * chains (e.g. the redo [scrollMessageBottom] pass) on the first streamed content growth. + */ @RequiresEdt fun followTail() { - followBottom(component.viewport.view === messages && tail) + if (following()) { + followBottom(true) + return + } + updateJump() } @RequiresEdt @@ -467,10 +481,7 @@ internal class SessionScroll( updateJump() return } - // Only re-pin when following. Routing the not-following case through followBottom(false) - // would bump seq and abort in-flight multi-pass chains (e.g. the redo scrollMessageBottom - // pass) on the first streamed content growth. When not following, just refresh the jump button. - if (following()) followTail() else updateJump() + followTail() } @RequiresEdt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt index f11b391bc001..e83c1547c62c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt @@ -36,6 +36,9 @@ import java.awt.Dimension * rendered through an [com.intellij.openapi.actionSystem.ActionToolbar]; each is invisible when it is * not enabled, so the dock never shows a lone action. The dock exposes its state to those actions via * [ChatDockKeys.DOCK]. Collapses to nothing unless it has a PR, changes, or an enabled action. + * + * The action row is offered only while the session is idle: an active turn ([setBusy]) withdraws it, + * a move in progress keeps it. The PR row stays through a turn — it is informational, not an action. */ internal class BranchDock( openDiff: () -> Unit, @@ -56,6 +59,7 @@ internal class BranchDock( private var files = emptyList() private var branch: BranchStatusDto? = null private var hasMessages = false + private var busy = false private var moving = false private var stage: MoveStage? = null @@ -102,6 +106,13 @@ internal class BranchDock( sync() } + @RequiresEdt + fun setBusy(value: Boolean) { + if (busy == value) return + busy = value + sync() + } + @RequiresEdt fun setMoveProgress(stage: MoveStage, detail: String?) { moving = stage != MoveStage.DONE && stage != MoveStage.ERROR @@ -125,7 +136,7 @@ internal class BranchDock( fun triggerMove() = onMove() - private fun dockActive(): Boolean = gitAvailable() && (hasMessages || files.isNotEmpty()) + private fun dockActive(): Boolean = gitAvailable() && !busy && (hasMessages || files.isNotEmpty()) private fun gitAvailable(): Boolean { val branch = branch ?: return false diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionScrollTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionScrollTest.kt index c5cc28fb08d1..cc5973a63883 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionScrollTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionScrollTest.kt @@ -1,17 +1,23 @@ package ai.kilocode.client.session +import ai.kilocode.client.agentManager.worktree.KiloWorktreeService import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.session.model.SessionState import ai.kilocode.client.session.ui.ModifiedFilesView import ai.kilocode.client.session.ui.SessionMessageListPanel +import ai.kilocode.client.session.ui.header.BranchDock import ai.kilocode.client.session.ui.prompt.PromptPanel import ai.kilocode.client.session.ui.selection.SessionCopyTarget import ai.kilocode.client.session.ui.style.SessionEditorStyle import ai.kilocode.client.session.ui.style.SessionUiStyle import ai.kilocode.client.session.views.tool.ShellToolView import ai.kilocode.client.session.views.tool.ToolView +import ai.kilocode.client.testing.FakeWorktreeRpcApi import ai.kilocode.client.ui.UiStyle +import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.ChatEventDto import ai.kilocode.rpc.dto.DiffFileDto +import ai.kilocode.rpc.dto.GhAvailability import ai.kilocode.rpc.dto.MessageErrorDto import ai.kilocode.rpc.dto.MessageSummaryDto import ai.kilocode.rpc.dto.MessageWithPartsDto @@ -23,6 +29,8 @@ import ai.kilocode.rpc.dto.QuestionRequestDto import ai.kilocode.rpc.dto.SessionRevertDto import ai.kilocode.rpc.dto.SessionStatusDto import ai.kilocode.rpc.dto.ToolRefDto +import com.intellij.openapi.application.ApplicationManager +import com.intellij.testFramework.replaceService import com.intellij.ui.EditorTextField import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBRadioButton @@ -832,6 +840,135 @@ class SessionScrollTest : SessionUiTestBase() { assertBottom(scrollBar()) } + // The branch dock sits outside the scroll pane, so it hiding on turn start (and reappearing on + // turn end) resizes the transcript viewport by its own row height. Bottom-following must survive + // both edges. + + fun `test dock hiding on turn start keeps the transcript following`() { + val dock = dockSession() + val bar = scrollBar() + setBottom(bar) + drainScroll() + assertTrue(dock.isVisible) + assertBottom(bar) + assertTrue(ui.scroll.following()) + + controller().model.setState(SessionState.Busy("running")) + drainScroll() + + assertFalse(dock.isVisible) + assertBottom(bar) + assertTrue(ui.scroll.following()) + } + + fun `test dock showing on turn end keeps the transcript following`() { + val dock = dockSession() + val bar = scrollBar() + setBottom(bar) + controller().model.setState(SessionState.Busy("running")) + drainScroll() + assertFalse(dock.isVisible) + + controller().model.setState(SessionState.Idle) + settle() + drainScroll() + + assertTrue(dock.isVisible) + assertBottom(bar) + assertTrue(ui.scroll.following()) + } + + // A wheel gesture that moves nothing (already pinned at the bottom) leaves the user-gesture flag + // set until the next adjustment event. Without an explicit re-pin the dock's own viewport resize + // is that event, and it reads as a deliberate scroll away from the bottom. + fun `test dock toggle keeps following after a wheel gesture at the bottom`() { + val dock = dockSession() + val bar = scrollBar() + setBottom(bar) + drainScroll() + wheelNoop() + + controller().model.setState(SessionState.Busy("running")) + drainScroll() + + assertFalse(dock.isVisible) + assertBottom(bar) + assertTrue(ui.scroll.following()) + + wheelNoop() + controller().model.setState(SessionState.Idle) + settle() + drainScroll() + + assertTrue(dock.isVisible) + assertBottom(bar) + assertTrue(ui.scroll.following()) + } + + // JViewport notifies the last-registered listener first, and a look and feel change re-installs + // the scroll pane UI's own viewport listener after ours. The platform's scrollbar sync then runs + // first, so the re-pin must not depend on listener order. + fun `test dock toggle keeps following after a look and feel change`() { + val dock = dockSession() + setBottom(scrollBar()) + drainScroll() + scrollComponent().updateUI() + drainScroll() + assertTrue(ui.scroll.following()) + wheelNoop() + + controller().model.setState(SessionState.Busy("running")) + drainScroll() + + assertFalse(dock.isVisible) + assertBottom(scrollBar()) + assertTrue(ui.scroll.following()) + } + + fun `test dock toggle preserves a scrolled-up position`() { + val dock = dockSession() + val bar = scrollBar() + setValue(bar, bottom(bar) / 2) + drainScroll() + val value = bar.value + assertFalse(ui.scroll.following()) + + controller().model.setState(SessionState.Busy("running")) + drainScroll() + + assertFalse(dock.isVisible) + assertEquals(value, bar.value) + assertFalse(ui.scroll.following()) + assertTrue(jumpButton().isVisible) + + controller().model.setState(SessionState.Idle) + settle() + drainScroll() + + assertTrue(dock.isVisible) + assertEquals(value, bar.value) + assertFalse(ui.scroll.following()) + assertTrue(jumpButton().isVisible) + } + + fun `test dock appearing at turn end does not break a recovered session open`() { + installWorktreeStatus() + rpc.history.addAll(history(24)) + rpc.statuses.value = mapOf("ses_test" to SessionStatusDto("busy")) + + ui = newUi(id = "ses_test") + settle() + drainScroll() + assertBottom(scrollBar()) + + emit(ChatEventDto.TurnClose("ses_test", "done")) + settle() + drainScroll() + + assertTrue(find(ui).isVisible) + assertBottom(scrollBar()) + } + fun `test replayed event during existing session open cannot cancel initial bottom`() { val gate = CompletableDeferred() rpc.historyGate = gate @@ -1376,6 +1513,27 @@ class SessionScrollTest : SessionUiTestBase() { assertTrue("value=${bar.value} expected=$expected", kotlin.math.abs(bar.value - expected) <= 1) } + /** Serves a branch status the dock accepts, so it really takes a row above the prompt. */ + private fun installWorktreeStatus() { + val worktree = FakeWorktreeRpcApi().apply { + branchResult = BranchStatusDto(branch = "main", availability = GhAvailability.OK) + } + ApplicationManager.getApplication() + .replaceService(KiloWorktreeService::class.java, KiloWorktreeService(scope, worktree), testRootDisposable) + } + + /** A filled transcript in a session whose branch dock is visible while idle. */ + private fun dockSession(): BranchDock { + installWorktreeStatus() + ui = newUi() + layout() + showMessages() + fillTranscript(24) + settle() + drainScroll() + return find(ui) + } + private fun button(text: String): JButton = findAll(ui).first { it.text == text } private fun icon(text: String): JButton = findAll(ui).first { it.toolTipText == text } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt index 13d871fe57c2..7a179b738c80 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt @@ -1,5 +1,6 @@ package ai.kilocode.client.session +import ai.kilocode.client.agentManager.worktree.KiloWorktreeService import ai.kilocode.client.session.SessionRef import ai.kilocode.client.session.model.Permission import ai.kilocode.client.session.model.PermissionMeta @@ -23,9 +24,12 @@ import ai.kilocode.client.session.ui.header.BranchDock import ai.kilocode.client.session.ui.header.SessionHeaderPanel import ai.kilocode.client.session.ui.style.SessionUiStyle import ai.kilocode.client.session.controller.SessionControllerEvent +import ai.kilocode.client.testing.FakeWorktreeRpcApi import ai.kilocode.client.ui.layout.Align +import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.ChatEventDto import ai.kilocode.rpc.dto.ConfigDto +import ai.kilocode.rpc.dto.GhAvailability import ai.kilocode.rpc.dto.KiloAppStateDto import ai.kilocode.rpc.dto.KiloAppStatusDto import ai.kilocode.rpc.dto.ProfileDto @@ -35,6 +39,8 @@ import com.intellij.util.ui.JBUI import ai.kilocode.client.session.views.permission.PermissionView import ai.kilocode.client.session.views.question.QuestionView import ai.kilocode.rpc.dto.MessageWithPartsDto +import com.intellij.openapi.application.ApplicationManager +import com.intellij.testFramework.replaceService import com.intellij.ui.components.JBScrollPane import java.awt.Dimension import javax.swing.JLayeredPane @@ -162,6 +168,28 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertNull(drop.dropTarget) } + fun `test dock hides while a turn runs`() { + val worktree = FakeWorktreeRpcApi().apply { + branchResult = BranchStatusDto(branch = "main", availability = GhAvailability.OK) + } + ApplicationManager.getApplication() + .replaceService(KiloWorktreeService::class.java, KiloWorktreeService(scope, worktree), testRootDisposable) + rpc.history.addAll(history(1)) + ui = newUi(id = "ses_test") + settle() + val dock = find(ui) + assertTrue(dock.isVisible) + + controller().model.setState(SessionState.Busy("running")) + + assertFalse(dock.isVisible) + + controller().model.setState(SessionState.Idle) + settle() + + assertTrue(dock.isVisible) + } + fun `test dock branch changes refresh on finish and revert`() { workspaceRpc.branchDiffs.clear() workspaceRpc.branchDiffs.add(DiffFileDto("src/A.kt", 2, 1)) @@ -366,14 +394,15 @@ class SessionUiLayoutTest : SessionUiTestBase() { val connection = find(ui) val prompt = find(ui) val root = find(ui) - val top = connection.y + // Anchored above the bottom container, not at a fixed y: a pending question makes the branch + // dock release its row, so the container itself gets shorter. + assertEquals(bottomTop(root, prompt) - SessionUiStyle.View.contentGap(), connection.y + connection.height) controller().model.setState(questionStateChanged()) layout() assertTrue(find(ui).isVisible) assertSame(find(ui), find(ui).parent) - assertEquals(top, connection.y) assertEquals(bottomTop(root, prompt) - SessionUiStyle.View.contentGap(), connection.y + connection.height) assertSame(find(ui), scrollView()) } @@ -387,14 +416,15 @@ class SessionUiLayoutTest : SessionUiTestBase() { val connection = find(ui) val prompt = find(ui) val root = find(ui) - val top = connection.y + // Anchored above the bottom container, not at a fixed y: a pending permission makes the branch + // dock release its row, so the container itself gets shorter. + assertEquals(bottomTop(root, prompt) - SessionUiStyle.View.contentGap(), connection.y + connection.height) controller().model.setState(permissionStateChanged()) layout() assertTrue(find(ui).isVisible) assertSame(find(ui), find(ui).parent) - assertEquals(top, connection.y) assertEquals(bottomTop(root, prompt) - SessionUiStyle.View.contentGap(), connection.y + connection.height) assertSame(find(ui), scrollView()) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt index 5f82ec61c4aa..08fdf2c0d119 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt @@ -72,6 +72,85 @@ class BranchDockTest : BasePlatformTestCase() { assertTrue(edt { dock.isVisible }) } + // ---- active session ---- + + fun `test dock hidden while session is busy`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + } + assertTrue(edt { dock.isVisible }) + + edt { dock.setBusy(true) } + assertFalse(edt { dock.isVisible }) + + edt { dock.setBusy(false) } + assertTrue(edt { dock.isVisible }) + } + + fun `test dock hidden while busy with local changes`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setChanges(listOf(DiffFileDto("src/A.kt", 2, 1))) + dock.setBusy(true) + } + assertFalse(edt { dock.isVisible }) + } + + fun `test dock keeps PR row while session is busy`() { + val dock = dock() + edt { + dock.setBranch( + BranchStatusDto( + branch = "feature-x", + worktree = false, + availability = GhAvailability.OK, + pr = WorktreePrDto("/repo", 7, GhState.OPEN, "https://pr/7", "Title"), + ), + ) + dock.setHasMessages(true) + dock.setBusy(true) + } + assertTrue(edt { dock.isVisible }) + } + + fun `test move action hidden while session is busy`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + dock.setBusy(true) + } + assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) + } + + fun `test new worktree action hidden while session is busy`() { + val dock = dockWithNewWorktree() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + dock.setBusy(true) + } + assertFalse(update(ChatNewWorktreeAction(), dock).isVisible) + } + + fun `test move progress keeps the row while session is busy`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + dock.setBusy(true) + dock.setMoveProgress(MoveStage.CREATING, null) + } + assertTrue(edt { dock.isVisible }) + val p = update(ChatMoveToWorktreeAction(), dock) + assertTrue(p.isVisible) + assertFalse(p.isEnabled) + assertEquals(KiloBundle.message("session.dock.progress.creating"), p.text) + } + // ---- Move to Worktree action ---- fun `test move action visible with messages`() { From ce5a71e5f07fb3ab50f4215278f6e2a1557ef148 Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 09:42:30 -0400 Subject: [PATCH 22/30] fix(jetbrains): show worktree progress in agent rows --- .changeset/worktree-progress-agent-row.md | 5 + .../kilocode/client/KiloToolWindowFactory.kt | 11 +- .../actions/ChatMoveToWorktreeAction.kt | 21 +--- .../client/agentManager/AgentManagerPanel.kt | 52 ++++----- .../agentManager/worktree/MoveToWorktree.kt | 72 ------------ .../worktree/WorktreeController.kt | 81 +++++++++++++- .../agentManager/worktree/WorktreeIcons.kt | 8 +- .../worktree/WorktreeSessionEditorKind.kt | 6 + .../worktree/WorktreeSessionEditorPanel.kt | 8 +- .../kilocode/client/session/SessionManager.kt | 6 + .../client/session/SessionSidePanelManager.kt | 9 ++ .../ai/kilocode/client/session/SessionUi.kt | 11 +- .../client/session/history/HistoryRows.kt | 14 +-- .../client/session/ui/header/BranchDock.kt | 28 ++--- .../client/ui/list/ActiveListModel.kt | 5 +- .../client/ui/list/ActiveListRenderer.kt | 11 +- .../kilocode/client/ui/list/ActiveListView.kt | 22 ++-- .../resources/messages/KiloBundle.properties | 11 +- .../agentManager/AgentManagerPanelTest.kt | 5 +- .../agentManager/WorktreeControllerTest.kt | 105 +++++++++++++++--- .../client/agentManager/WorktreeIconsTest.kt | 22 ++-- .../WorktreeSessionEditorPanelTest.kt | 2 +- .../client/session/SessionUiLayoutTest.kt | 29 +++++ .../session/history/HistoryControllerTest.kt | 6 +- .../session/ui/header/BranchDockTest.kt | 38 ++----- .../client/ui/list/ActiveListSelectionTest.kt | 12 ++ .../kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt | 1 - 27 files changed, 342 insertions(+), 259 deletions(-) create mode 100644 .changeset/worktree-progress-agent-row.md delete mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/MoveToWorktree.kt diff --git a/.changeset/worktree-progress-agent-row.md b/.changeset/worktree-progress-agent-row.md new file mode 100644 index 000000000000..7b3e880cecf4 --- /dev/null +++ b/.changeset/worktree-progress-agent-row.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Show worktree creation and move progress in the Agent Manager row instead of the chat dock. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt index 9cc0c3f60925..761c0581b53a 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt @@ -99,6 +99,7 @@ internal class KiloToolWindowSetupService( workspace.directory, cs, activity = project.service().activity, + abort = { id, dir -> project.service().abort(id, dir) }, ) val agentManagerPanel = AgentManagerPanel(manager, worktrees, project) @@ -138,13 +139,17 @@ internal class KiloToolWindowSetupService( agentContent.putUserData(ToolWindow.SHOW_CONTENT_ICON, true) toolWindow.contentManager.addContent(chatContent) toolWindow.contentManager.addContent(agentContent) + val agents = { toolWindow.contentManager.setSelectedContent(agentContent, true) } // The chat branch dock's "New Worktree" action switches to the Agent Manager tab and // opens its New Worktree dialog, matching the VS Code sidebar dock. manager.onNewWorktree = { Telemetry.send("New Worktree Clicked", mapOf("surface" to "chat_dock")) - agentManagerPanel.configure { - toolWindow.contentManager.setSelectedContent(agentContent) - } + agents() + agentManagerPanel.configure() + } + manager.onMoveToWorktree = { id, dir -> + agents() + agentManagerPanel.move(id, dir) } val listener = object : ContentManagerListener { override fun selectionChanged(event: ContentManagerEvent) { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt index b368d73c0b4e..cc41f74f0154 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt @@ -2,19 +2,16 @@ package ai.kilocode.client.actions import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.session.ui.header.ChatDockKeys -import ai.kilocode.rpc.dto.MoveStage import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.IconLoader -import com.intellij.ui.AnimatedIcon /** * "Move to Worktree" action shown in the chat branch dock. Visible only when there is something to - * move (a conversation or local changes). While a move runs it stays visible but disabled, showing a - * spinner and the current stage. + * move (a conversation or local changes). */ class ChatMoveToWorktreeAction : AnAction(), DumbAware { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT @@ -26,14 +23,6 @@ class ChatMoveToWorktreeAction : AnAction(), DumbAware { e.presentation.isEnabledAndVisible = false return } - if (dock.moving()) { - e.presentation.isVisible = true - e.presentation.isEnabled = false - e.presentation.icon = AnimatedIcon.Default.INSTANCE - e.presentation.text = progressLabel(dock.moveStage()) - e.presentation.description = null - return - } e.presentation.isEnabledAndVisible = dock.moveEnabled() e.presentation.icon = BRANCH e.presentation.text = KiloBundle.message("session.dock.move") @@ -44,14 +33,6 @@ class ChatMoveToWorktreeAction : AnAction(), DumbAware { e.getData(ChatDockKeys.DOCK)?.triggerMove() } - private fun progressLabel(stage: MoveStage?): String = when (stage) { - MoveStage.CAPTURING -> KiloBundle.message("session.dock.progress.capturing") - MoveStage.CREATING -> KiloBundle.message("session.dock.progress.creating") - MoveStage.TRANSFERRING -> KiloBundle.message("session.dock.progress.transferring") - MoveStage.FORKING -> KiloBundle.message("session.dock.progress.forking") - else -> KiloBundle.message("session.dock.move") - } - private fun moveTooltip(count: Int): String = when (count) { 0 -> KiloBundle.message("session.dock.move.tooltip.empty") 1 -> KiloBundle.message("session.dock.move.tooltip.one") diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 1765da0e001a..6bcd55ff2699 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -13,7 +13,7 @@ import ai.kilocode.client.agentManager.worktree.WorktreeEditorMatchers import ai.kilocode.client.agentManager.worktree.WorktreeSessionEditorMatcher import ai.kilocode.client.agentManager.worktree.WorktreeSessionEditorKind import ai.kilocode.client.agentManager.worktree.WorktreeTitle -import ai.kilocode.client.agentManager.worktree.ensureWorktreeSessionEditorKind +import ai.kilocode.client.agentManager.worktree.openWorktreeSession import ai.kilocode.client.agentManager.worktree.normalizeWorktreePath import ai.kilocode.client.agentManager.worktree.worktreeSessionParams import ai.kilocode.client.ui.prTooltip @@ -95,7 +95,7 @@ class AgentManagerPanel( (row as? WorktreeRow)?.dto?.takeIf { canRename(it) || canDelete(it) || canOpenPr(it) || canOpenDiff(it) } }), reorder = ActiveListReorder( - movable = { row -> row is WorktreeRow && !row.current && !row.pending && !row.deleting }, + movable = { row -> row is WorktreeRow && !row.current && row.progress == null }, onMove = { move -> controller.reorder(move.keys) }, ), ) @@ -114,9 +114,10 @@ class AgentManagerPanel( // Focus the list so the freshly created worktree renders as an active selection rather // than the inactive highlight it would get while focus stays on the toolbar. if (list.select(key)) list.focusList() - item(key)?.takeIf { !controller.isPending(it.id) }?.let { open(it, focus = false) } + item(key)?.takeIf { controller.progress(it.id) == null }?.let { open(it, focus = false) } } controller.onCreateFailure = { err -> notifyCreateFailed(err) } + controller.onMoveFailure = { err -> notifyMoveFailed(err) } controller.onRemoveSuccess = { item, index -> onRemoved(item, index) } controller.onActivityChanged = { sync() @@ -155,7 +156,7 @@ class AgentManagerPanel( } /** Opens the New Worktree dialog. */ - fun configure(afterClose: (() -> Unit)? = null) { + fun configure() { val target = project ?: return NewWorktreeDialog( this, @@ -168,9 +169,10 @@ class AgentManagerPanel( controller.create(branch, base, prompt = prompt) }, ).show() - afterClose?.invoke() } + internal fun move(sessionId: String, directory: String) = controller.move(sessionId, directory) + private fun remove(item: WorktreeDto, force: Boolean) { controller.remove(item, force, onFailure = { result -> notifyFailed(item, result, force) }) } @@ -205,9 +207,8 @@ class AgentManagerPanel( private fun open(item: WorktreeDto, focus: Boolean) { val target = project ?: return - if (controller.isPending(item.id)) return - ensureWorktreeSessionEditorKind() - target.service().open(WorktreeSessionEditorKind.ID, worktreeSessionParams(item), focus) + if (controller.progress(item.id) != null) return + openWorktreeSession(target, item, controller.takeSession(item.id), focus) } private fun close(item: WorktreeDto) { @@ -226,13 +227,13 @@ class AgentManagerPanel( /** The PR URL for [item], or null when it has none or is not in a stable, openable state. */ private fun prUrl(item: WorktreeDto?): String? { if (item == null || item.main) return null - if (controller.isPending(item.id) || controller.isDeleting(item.id)) return null + if (controller.progress(item.id) != null) return null return prs[normalizeWorktreePath(item.path)]?.url } internal fun canOpenDiff(item: WorktreeDto?): Boolean { if (item == null || item.main || project == null) return false - return !controller.isPending(item.id) && !controller.isDeleting(item.id) + return controller.progress(item.id) == null } internal fun openDiff(item: WorktreeDto) { @@ -255,8 +256,7 @@ class AgentManagerPanel( } private fun deletable(item: WorktreeDto?): Boolean { - if (!worktreeDeletable(item, item?.id?.let(controller::isPending) == true)) return false - return item?.id?.let(controller::isDeleting) != true + return worktreeDeletable(item, item?.id?.let(controller::progress) != null) } private fun renameable(item: WorktreeDto?): Boolean { @@ -266,7 +266,7 @@ class AgentManagerPanel( private fun renameVisible(item: WorktreeDto?): Boolean { if (item == null || item.main) return false - return !controller.isPending(item.id) && !controller.isDeleting(item.id) + return controller.progress(item.id) == null } /** @@ -311,6 +311,10 @@ class AgentManagerPanel( KiloNotifications.error(project, KiloBundle.message("worktree.create.failed.title"), err) } + private fun notifyMoveFailed(err: String?) { + KiloNotifications.error(project, KiloBundle.message("worktree.move.failed.title"), err) + } + /** Surfaces a failed removal; offers a force-delete retry when git reported a lock. */ private fun notifyFailed(item: WorktreeDto, result: RemoveWorktreeResultDto, forced: Boolean) { val title = KiloBundle.message("worktree.delete.failed.title", item.name) @@ -352,8 +356,7 @@ class AgentManagerPanel( val current = controller.current?.let { item -> WorktreeRow( item, - pending = false, - deleting = false, + progress = null, kind = controller.kind(item.path), stats = null, pr = null, @@ -368,8 +371,7 @@ class AgentManagerPanel( service().putPr(item.path, pull) WorktreeRow( item, - controller.isPending(item.id), - controller.isDeleting(item.id), + controller.progress(item.id), controller.kind(item.path), stats[key], pull, @@ -418,6 +420,7 @@ class AgentManagerPanel( override fun dispose() { controller.onSelect = null controller.onCreateFailure = null + controller.onMoveFailure = null controller.onRemoveSuccess = null controller.onActivityChanged = null } @@ -469,8 +472,7 @@ class AgentManagerPanel( */ private inner class WorktreeRow( val dto: WorktreeDto, - val pending: Boolean, - override val deleting: Boolean, + override val progress: String?, val kind: SessionActivityKind?, val stats: WorktreeStatsDto?, val pr: WorktreePrDto?, @@ -481,13 +483,13 @@ class AgentManagerPanel( override val title: String get() = if (current) dto.branch else WorktreeTitle.text(dto.name, dto.path, pr) override val description: String get() = WorktreeTitle.fallback(dto.path) override val tooltip: String? get() = null - override val icon = WorktreeIcons.forRow(pending, kind, dto.locked, current) + override val icon = WorktreeIcons.forRow(progress != null, kind, dto.locked, current) override val section: String? get() = if (current) null else KiloBundle.message("worktree.section.local") override val search: String get() = listOfNotNull(dto.name, dto.branch, dto.path, dto.lockReason).joinToString(" ") private val customName: String? get() = WorktreeTitle.custom(dto.name, dto.path) override val metrics: ActiveListMetrics? get() { - if (pending || deleting) return null + if (progress != null) return null val s = stats val p = pr if (s == null && p == null) return null @@ -506,8 +508,7 @@ class AgentManagerPanel( override fun equals(other: Any?): Boolean { val row = other as? WorktreeRow ?: return false return dto == row.dto && - pending == row.pending && - deleting == row.deleting && + progress == row.progress && kind == row.kind && stats == row.stats && pr == row.pr && @@ -516,8 +517,7 @@ class AgentManagerPanel( override fun hashCode(): Int { var result = dto.hashCode() - result = 31 * result + pending.hashCode() - result = 31 * result + deleting.hashCode() + result = 31 * result + (progress?.hashCode() ?: 0) result = 31 * result + (kind?.hashCode() ?: 0) result = 31 * result + (stats?.hashCode() ?: 0) result = 31 * result + (pr?.hashCode() ?: 0) @@ -537,4 +537,4 @@ class AgentManagerPanel( } } -internal fun worktreeDeletable(item: WorktreeDto?, pending: Boolean): Boolean = item != null && !item.main && !pending +internal fun worktreeDeletable(item: WorktreeDto?, busy: Boolean): Boolean = item != null && !item.main && !busy diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/MoveToWorktree.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/MoveToWorktree.kt deleted file mode 100644 index 55f79a3510fe..000000000000 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/MoveToWorktree.kt +++ /dev/null @@ -1,72 +0,0 @@ -package ai.kilocode.client.agentManager.worktree - -import ai.kilocode.client.KiloNotifications -import ai.kilocode.client.app.KiloSessionService -import ai.kilocode.client.plugin.KiloBundle -import ai.kilocode.client.telemetry.Telemetry -import ai.kilocode.client.vfs.KiloVfsManager -import ai.kilocode.log.KiloLog -import ai.kilocode.rpc.dto.MoveProgressDto -import ai.kilocode.rpc.dto.MoveStage -import com.intellij.openapi.components.service -import com.intellij.openapi.project.Project -import com.intellij.util.concurrency.annotations.RequiresEdt -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * Sidebar "Move to Worktree": aborts the running session, generates a friendly branch name, then - * drives the backend move flow (capture → create → transfer → fork). On success it opens the - * worktree session editor on the forked session; on error it notifies through the worktree pattern. - * The source sidebar session stays in the sidebar (aborted, not deleted), matching VS Code fork - * semantics. - */ -internal class MoveToWorktree( - private val project: Project, - private val cs: CoroutineScope, -) { - private companion object { - private val LOG = KiloLog.create(MoveToWorktree::class.java) - } - - /** [progress] is invoked on the EDT for each stage so the dock button can reflect it. */ - @RequiresEdt - fun launch(directory: String, sessionId: String, progress: (MoveStage, String?) -> Unit) { - cs.launch { - runCatching { service().abort(sessionId, directory) } - .onFailure { LOG.info("worktree move: abort failed (session may be idle): ${it.message}") } - val known = service().listBranches(directory).branches.toSet() - val branch = WorktreeNames.generate(known) - var stage = MoveStage.CAPTURING - val flow = service().moveToWorktree(directory, sessionId, branch) - flow.collect { event -> - if (event.stage != MoveStage.ERROR) stage = event.stage - withContext(Dispatchers.Main) { handle(event, stage, progress) } - } - } - } - - @RequiresEdt - private fun handle(event: MoveProgressDto, failing: MoveStage, progress: (MoveStage, String?) -> Unit) { - progress(event.stage, event.detail) - when (event.stage) { - MoveStage.DONE -> { - val worktree = event.worktree ?: return - ensureWorktreeSessionEditorKind() - project.service().open( - WorktreeSessionEditorKind.ID, - worktreeSessionParams(worktree, session = event.session), - ) - Telemetry.send("Continue in Worktree", mapOf("surface" to "sidebar")) - } - MoveStage.ERROR -> { - LOG.warn("worktree move failed stage=$failing error=${event.error}") - KiloNotifications.error(project, KiloBundle.message("session.dock.move.failed.title"), event.error) - Telemetry.send("Continue in Worktree Failed", mapOf("stage" to failing.name)) - } - else -> Unit - } - } -} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt index 8e0d4c31ee7e..1e1408342f46 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt @@ -6,18 +6,19 @@ import ai.kilocode.client.util.edt import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.rpc.dto.CreateWorktreeRequestDto import ai.kilocode.rpc.dto.CreateWorktreeResultDto +import ai.kilocode.rpc.dto.MoveStage import ai.kilocode.rpc.dto.RemoveWorktreeResultDto import ai.kilocode.rpc.dto.SessionActivityDto import ai.kilocode.rpc.dto.WorktreeDto import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.ui.CollectionListModel +import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch -import java.util.Collections /** * Owns the worktree list model and drives the [KiloWorktreeService] off the EDT. Model mutations @@ -28,13 +29,17 @@ class WorktreeController( val directory: String, private val cs: CoroutineScope, activity: StateFlow> = MutableStateFlow(emptyMap()), + private val abort: suspend (String, String) -> Unit = { _, _ -> }, private val telemetry: (String, Map) -> Unit = { event, props -> Telemetry.send(event, props) }, ) { val model = CollectionListModel() private val pending = LinkedHashMap() - private val deleting = Collections.synchronizedSet(LinkedHashSet()) + private val tasks = LinkedHashMap() + private val moves = LinkedHashSet() + private val sessions = LinkedHashMap() var onSelect: ((String) -> Unit)? = null var onCreateFailure: ((String?) -> Unit)? = null + var onMoveFailure: ((String?) -> Unit)? = null var onRemoveSuccess: ((WorktreeDto, Int) -> Unit)? = null var onActivityChanged: (() -> Unit)? = null @@ -73,7 +78,9 @@ class WorktreeController( fun isPending(id: String): Boolean = id in pending - fun isDeleting(id: String): Boolean = id in deleting + fun progress(id: String): String? = tasks[id] + + fun takeSession(id: String): String? = sessions.remove(id) fun kind(path: String): SessionActivityKind? = kinds[normalizeWorktreePath(path)] @@ -116,6 +123,7 @@ class WorktreeController( val temp = WorktreeDto(id, branch, branch, id) edt { pending[temp.id] = temp + tasks[temp.id] = KiloBundle.message("worktree.progress.creating") model.add(temp) onSelect?.invoke(temp.id) } @@ -130,6 +138,7 @@ class WorktreeController( val temp = WorktreeDto(id, KiloBundle.message("worktree.import.pr.section"), "", id) edt { pending[temp.id] = temp + tasks[temp.id] = KiloBundle.message("worktree.progress.creating") model.add(temp) onSelect?.invoke(temp.id) } @@ -148,6 +157,7 @@ class WorktreeController( val created = result.worktree edt { pending.remove(temp.id) + tasks.remove(temp.id) val idx = model.getElementIndex(temp) if (created != null) { if (idx >= 0) model.setElementAt(created, idx) else model.add(created) @@ -174,13 +184,14 @@ class WorktreeController( onSuccess: () -> Unit = {}, onFailure: (RemoveWorktreeResultDto) -> Unit = {}, ) { - if (!deleting.add(dto.id)) return + if (dto.id in tasks) return + tasks[dto.id] = KiloBundle.message("common.deleting") edt { refresh(dto) } cs.launch { val result = service.remove(directory, dto.path, dto.branch, force) if (result.ok) { edt { - deleting.remove(dto.id) + tasks.remove(dto.id) val index = model.getElementIndex(dto) model.remove(dto) cache().remove(dto.path) @@ -193,7 +204,7 @@ class WorktreeController( // Removal failed: git still tracks the worktree. Keep the row and reconcile with // ground truth so a stale optimistic delete can't make the entry reappear later. edt { - deleting.remove(dto.id) + tasks.remove(dto.id) refresh(dto) telemetry( "Worktree Delete Failed", @@ -205,6 +216,46 @@ class WorktreeController( } } + @RequiresEdt + fun move(sessionId: String, source: String = directory) { + if (!moves.add(sessionId)) return + val branch = suggestName() + val temp = WorktreeDto("pending:$branch:${System.nanoTime()}", branch, branch, "pending:$branch") + pending[temp.id] = temp + tasks[temp.id] = label(MoveStage.CAPTURING) + model.add(temp) + onSelect?.invoke(temp.id) + cs.launch { + var stage = MoveStage.CAPTURING + runCatching { + abort(sessionId, source) + service.moveToWorktree(source, sessionId, branch).collect { event -> + edt { + if (event.stage != MoveStage.ERROR) stage = event.stage + tasks[temp.id] = label(event.stage) + refresh(temp) + when (event.stage) { + MoveStage.DONE -> { + moves.remove(sessionId) + pending.remove(temp.id) + tasks.remove(temp.id) + val worktree = event.worktree ?: return@edt + val idx = model.getElementIndex(temp) + if (idx >= 0) model.setElementAt(worktree, idx) else model.add(worktree) + cache().put(worktree) + event.session?.let { sessions[worktree.id] = it } + onSelect?.invoke(worktree.id) + telemetry("Continue in Worktree", mapOf("surface" to "sidebar")) + } + MoveStage.ERROR -> failMove(sessionId, temp, event.error, stage) + else -> Unit + } + } + } + }.onFailure { err -> edt { failMove(sessionId, temp, err.message, stage) } } + } + } + fun rename( dto: WorktreeDto, name: String, @@ -281,6 +332,24 @@ class WorktreeController( return (0 until model.size).firstOrNull { model.getElementAt(it).id == id } ?: -1 } + private fun failMove(session: String, temp: WorktreeDto, err: String?, stage: MoveStage) { + moves.remove(session) + pending.remove(temp.id) + tasks.remove(temp.id) + model.remove(temp) + onMoveFailure?.invoke(err) + telemetry("Continue in Worktree Failed", mapOf("stage" to stage.name)) + } + + private fun label(stage: MoveStage): String = when (stage) { + MoveStage.CAPTURING -> KiloBundle.message("worktree.progress.capturing") + MoveStage.CREATING -> KiloBundle.message("worktree.progress.creating") + MoveStage.TRANSFERRING -> KiloBundle.message("worktree.progress.transferring") + MoveStage.FORKING -> KiloBundle.message("worktree.progress.starting") + MoveStage.DONE -> "" + MoveStage.ERROR -> "" + } + private fun cache(): WorktreeNameCache { return ApplicationManager.getApplication().service() } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt index 9f9d789c4f58..5fe84fbd5bfe 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeIcons.kt @@ -22,16 +22,16 @@ internal object WorktreeIcons { /** * Leading icon for a worktree row. At rest the row shows what it is — the local machine, a locked * checkout, or a branch checkout — while a running or waiting session takes the slot over so the - * list still surfaces activity at a glance. Creation ([pending]) outranks all of it, and an - * errored session falls back to the resting glyph instead of shouting in the leading slot. + * list still surfaces activity at a glance. An operation on the row ([busy]) outranks all of it, + * and an errored session falls back to the resting glyph instead of shouting in the leading slot. */ fun forRow( - pending: Boolean, + busy: Boolean, kind: SessionActivityKind? = null, locked: Boolean = false, current: Boolean = false, ): Icon { - if (pending) return spinner + if (busy) return spinner return when (kind) { SessionActivityKind.RUNNING -> running SessionActivityKind.QUESTION, diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt index e5c263405528..569bbc7ae2e5 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt @@ -7,6 +7,7 @@ import ai.kilocode.client.session.SessionUiFactory import ai.kilocode.client.vfs.KiloEditorKind import ai.kilocode.client.vfs.KiloEditorKindRegistry import ai.kilocode.client.vfs.KiloVirtualFile +import ai.kilocode.client.vfs.KiloVfsManager import ai.kilocode.rpc.dto.WorktreeDto import com.intellij.openapi.Disposable import com.intellij.openapi.components.service @@ -62,3 +63,8 @@ internal fun unregisterWorktreeSessionEditorKind() { internal fun worktreeSessionParams(item: WorktreeDto, session: String? = null): Map = linkedMapOf( "path" to item.path, ).apply { session?.takeIf { it.isNotBlank() }?.let { put("session", it) } } + +internal fun openWorktreeSession(project: Project, worktree: WorktreeDto, session: String? = null, focus: Boolean = true) { + ensureWorktreeSessionEditorKind() + project.service().open(WorktreeSessionEditorKind.ID, worktreeSessionParams(worktree, session), focus) +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt index 7693b836d813..d87cb64c021d 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt @@ -557,7 +557,7 @@ class WorktreeSessionEditorPanel( private inner class SessionRow( val session: SessionDto, val kind: SessionActivityKind?, - override val deleting: Boolean = false, + private val deleting: Boolean = false, // Live title of the open session, if any; reflects the agent-generated name as it streams in // before the listed snapshot catches up. private val live: String? = null, @@ -572,11 +572,9 @@ class WorktreeSessionEditorPanel( return name } override val tooltip: String get() = title + override val progress: String? get() = if (deleting) KiloBundle.message("common.deleting") else null override val badges: List - get() { - if (deleting) return emptyList() - return listOfNotNull(kind?.let { ActiveListBadge(it.label(), it.style()) }) - } + get() = listOfNotNull(kind?.let { ActiveListBadge(it.label(), it.style()) }) override val section: String get() = HistoryTime.title(HistoryTime.section(item)) override val search: String get() = listOf(session.title, session.id, session.directory).joinToString(" ") } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt index b3404a7106fe..f64c359163e7 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt @@ -21,6 +21,12 @@ interface SessionManager { /** Opens the New Worktree flow. No-op unless [supportsNewWorktree] is true. */ fun newWorktree() {} + /** Whether this surface can move the current chat into a worktree (sidebar only). */ + val supportsMoveToWorktree: Boolean get() = false + + /** Opens the Move to Worktree flow. No-op unless [supportsMoveToWorktree] is true. */ + fun moveToWorktree(sessionId: String, directory: String) {} + fun showHistory(back: (() -> Unit)? = null) fun openSession(ref: SessionRef) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt index 6a7714e4b241..df20db529669 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt @@ -52,12 +52,21 @@ class SessionSidePanelManager( /** Wired by the tool window to open the Agent Manager's New Worktree flow from the chat dock. */ var onNewWorktree: (() -> Unit)? = null + /** Wired by the tool window to move the current chat into an Agent Manager worktree row. */ + var onMoveToWorktree: ((String, String) -> Unit)? = null + override val supportsNewWorktree: Boolean get() = onNewWorktree != null + override val supportsMoveToWorktree: Boolean get() = onMoveToWorktree != null + override fun newWorktree() { onNewWorktree?.invoke() } + override fun moveToWorktree(sessionId: String, directory: String) { + onMoveToWorktree?.invoke(sessionId, directory) + } + val defaultFocusedComponent: JComponent? get() = currentUi()?.defaultFocusedComponent ?: (panel as? HistoryPanel)?.defaultFocusedComponent @RequiresEdt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt index cdb6c724db00..7641bddc708e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt @@ -44,7 +44,6 @@ import ai.kilocode.client.session.ui.attachment.attachmentParams import ai.kilocode.client.session.ui.attachment.ensureAttachmentEditorKind import ai.kilocode.client.session.ui.attachment.isEmbeddedAttachment import ai.kilocode.client.agentManager.worktree.KiloWorktreeService -import ai.kilocode.client.agentManager.worktree.MoveToWorktree import ai.kilocode.client.session.ui.header.BranchDock import ai.kilocode.client.session.ui.header.SessionHeaderPanel import ai.kilocode.client.session.ui.selection.SessionContextMenu @@ -201,8 +200,6 @@ class SessionUi( private var bottom: JComponent? = null - private val move by lazy { MoveToWorktree(project, cs) } - internal lateinit var scroll: SessionScroll private lateinit var question: QuestionView @@ -430,7 +427,8 @@ class SessionUi( if (!readonly && showBranchDock()) { val owner = manager val newWorktree = if (owner?.supportsNewWorktree == true) owner::newWorktree else null - dock = BranchDock(openDiff = ::openBranchChanges, onMove = ::moveToWorktree, onNewWorktree = newWorktree) + val move = if (owner?.supportsMoveToWorktree == true) ::moveToWorktree else null + dock = BranchDock(openDiff = ::openBranchChanges, onMove = move, onNewWorktree = newWorktree) } scroll = SessionScroll(root, sessionContent, messageBody, blankBody) @@ -990,12 +988,11 @@ class SessionUi( } } - /** Starts the Move to Worktree flow for the current session, wiring progress into the dock. */ + /** Starts the Move to Worktree flow for the current session through the side-panel manager. */ @RequiresEdt private fun moveToWorktree() { - val dock = dock ?: return val id = controller.id ?: return - move.launch(controller.sessionDirectory, id) { stage, detail -> dock.setMoveProgress(stage, detail) } + manager?.moveToWorktree(id, controller.sessionDirectory) } @RequiresEdt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryRows.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryRows.kt index 3014e826adc3..d9d4d5d1a8d8 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryRows.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/history/HistoryRows.kt @@ -1,5 +1,6 @@ package ai.kilocode.client.session.history +import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.client.ui.list.ActiveListBadge import ai.kilocode.client.ui.list.ActiveListCell @@ -12,22 +13,17 @@ internal data class LocalHistoryRow( private val text: String, private val kind: SessionActivityKind?, override val section: String?, - override val deleting: Boolean, + private val deleting: Boolean, ) : ActiveListItem { override val key: String get() = item.id override val title: String get() = text override val trailing: String get() = HistoryTime.relative(item) override val search: String get() = listOfNotNull(text, item.id, item.directory).joinToString(" ") + override val progress: String? get() = if (deleting) KiloBundle.message("common.deleting") else null override val badges: List - get() { - if (deleting) return emptyList() - return listOfNotNull(kind?.let { ActiveListBadge(it.label(), it.style()) }) - } + get() = listOfNotNull(kind?.let { ActiveListBadge(it.label(), it.style()) }) override val cells: List - get() { - if (deleting) return emptyList() - return listOf(activeListRenameCell(), activeListDeleteCell()) - } + get() = listOf(activeListRenameCell(), activeListDeleteCell()) } internal data class CloudHistoryRow( diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt index e83c1547c62c..20f37ce60e00 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt @@ -11,7 +11,6 @@ import ai.kilocode.client.ui.layout.align import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.DiffFileDto import ai.kilocode.rpc.dto.GhAvailability -import ai.kilocode.rpc.dto.MoveStage import com.intellij.ide.ActivityTracker import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DataSink @@ -37,12 +36,12 @@ import java.awt.Dimension * not enabled, so the dock never shows a lone action. The dock exposes its state to those actions via * [ChatDockKeys.DOCK]. Collapses to nothing unless it has a PR, changes, or an enabled action. * - * The action row is offered only while the session is idle: an active turn ([setBusy]) withdraws it, - * a move in progress keeps it. The PR row stays through a turn — it is informational, not an action. + * The action row is offered only while the session is idle: an active turn ([setBusy]) withdraws it. + * The PR row stays through a turn — it is informational, not an action. */ internal class BranchDock( openDiff: () -> Unit, - private val onMove: () -> Unit, + private val onMove: (() -> Unit)?, private val onNewWorktree: (() -> Unit)? = null, ) : BorderLayoutPanel(), SessionEditorStyleTarget, UiDataProvider { private val core = PrHeaderView(openDiff) @@ -60,8 +59,6 @@ internal class BranchDock( private var branch: BranchStatusDto? = null private var hasMessages = false private var busy = false - private var moving = false - private var stage: MoveStage? = null init { isOpaque = true @@ -113,28 +110,17 @@ internal class BranchDock( sync() } - @RequiresEdt - fun setMoveProgress(stage: MoveStage, detail: String?) { - moving = stage != MoveStage.DONE && stage != MoveStage.ERROR - this.stage = if (moving) stage else null - sync() - } - // ---- state read by the toolbar actions ---- - fun newWorktreeEnabled(): Boolean = onNewWorktree != null && dockActive() && !moving - - fun moveEnabled(): Boolean = dockActive() && !moving - - fun moving(): Boolean = moving + fun newWorktreeEnabled(): Boolean = onNewWorktree != null && dockActive() - fun moveStage(): MoveStage? = stage + fun moveEnabled(): Boolean = onMove != null && dockActive() fun changeCount(): Int = files.size fun triggerNewWorktree() = onNewWorktree?.invoke() ?: Unit - fun triggerMove() = onMove() + fun triggerMove() = onMove?.invoke() ?: Unit private fun dockActive(): Boolean = gitAvailable() && !busy && (hasMessages || files.isNotEmpty()) @@ -151,7 +137,7 @@ internal class BranchDock( // PR present -> the informational PR header; otherwise the centered action row. core.isVisible = pull != null - val rowVisible = pull == null && (dockActive() || moving) + val rowVisible = pull == null && dockActive() actionRow.isVisible = rowVisible val next = pull != null || rowVisible diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt index 51cecbdea447..bce694274797 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListModel.kt @@ -109,7 +109,8 @@ internal interface ActiveListItem { val metrics: ActiveListMetrics? get() = null val cells: List get() = emptyList() val disabled: Boolean get() = false - val deleting: Boolean get() = false + /** Non-null while a background operation owns this row; the text is shown trailing. */ + val progress: String? get() = null /** Extra text matched by the filter field in addition to [title]; null matches title only. */ val search: String? get() = null } @@ -126,7 +127,7 @@ internal fun activeListVisibleCells( menu: Boolean = false, ): List { if (item.disabled) return emptyList() - if (item.deleting) return emptyList() + if (item.progress != null) return emptyList() val cells = item.cells.filter { active || it.alwaysVisible } if (!menu) return cells return cells + activeListMenuCell() diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt index 276767e2dcd0..9c603785a2bc 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListRenderer.kt @@ -1,7 +1,6 @@ package ai.kilocode.client.ui.list import ai.kilocode.client.agentManager.worktree.WorktreeStatsView -import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.session.ui.PickerRow import ai.kilocode.client.ui.FilledBadgeIcon import ai.kilocode.client.ui.LayeredOverlayPanel @@ -192,7 +191,7 @@ internal class ActiveListRenderer( val active = selected && (focused || list.hasFocus() || (list as? ActiveListActive)?.active() == true) val fg = UIUtil.getListForeground(active, active || focused) val weak = UiStyle.Colors.weak() - val titleFg = if (value.deleting) weak else fg + val titleFg = if (value.progress != null) weak else fg val section = activeListSectionTitle(model.items, index) background = list.background @@ -239,13 +238,13 @@ internal class ActiveListRenderer( JBUI.Borders.empty() } desc.foreground = weak - val data = if (value.deleting) null else value.metrics + val data = if (value.progress != null) null else value.metrics metrics.update(data?.let { WorktreeStatsDto("", it.additions, it.deletions, it.ahead, it.behind) }, data?.pr, data?.prTooltip ?: data?.pr?.text) metrics.setActions(data?.onChanges, data?.onPr) - val end = if (value.deleting) KiloBundle.message("common.deleting") else value.trailing.orEmpty() + val end = value.progress ?: value.trailing.orEmpty() trail.text = end trail.isVisible = end.isNotBlank() && data == null - metrics.isVisible = data != null && !value.deleting + metrics.isVisible = data != null // Hide the wrapper too so a metrics-less row does not reserve the trailing gap on its // description, and collapse the whole second row when it would be empty so title-only rows // stay vertically centered. @@ -347,7 +346,7 @@ internal class ActiveListRenderer( } private fun syncBadges(item: ActiveListItem) { - val items = if (item.deleting) emptyList() else item.badges + val items = if (item.progress != null) emptyList() else item.badges while (badges.componentCount > items.size) badges.remove(badges.componentCount - 1) while (badges.componentCount < items.size) { badges.add(JBLabel().apply { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt index bb7cd3ae5057..79f3dfa42dd9 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt @@ -144,7 +144,7 @@ internal class ActiveListView( if (selection(e)) return val hit = hit(e, enabled = false) ?: return if (hit.id != null) return - if (hit.item.deleting) return + if (hit.item.progress != null) return if (!openOnClick) { onClick?.invoke(hit.item) ?: return e.consume() @@ -158,7 +158,7 @@ internal class ActiveListView( if (e.clickCount != 2 || !UIUtil.isActionClick(e, MouseEvent.MOUSE_CLICKED, true)) return val hit = hit(e, enabled = false) ?: return if (hit.id != null) return - if (hit.item.deleting) return + if (hit.item.progress != null) return val action = onOpen if (action != null) action(hit.item, true) else activate(hit.item) e.consume() @@ -174,7 +174,7 @@ internal class ActiveListView( press = null val hit = hit(e) ?: return if (hit.item.key != down.key || hit.id != down.id) return - if (hit.item.deleting) return + if (hit.item.progress != null) return fire(hit.item, down.id) e.consume() } @@ -517,7 +517,7 @@ internal class ActiveListView( private fun open(focus: Boolean) { val item = active() ?: return if (item is ActiveListGap) return - if (item.deleting) return + if (item.progress != null) return val action = onOpen if (action != null) { action(item, focus) @@ -529,7 +529,7 @@ internal class ActiveListView( private fun source() { val item = list.selectedValue ?: return if (item is ActiveListGap) return - if (item.deleting) return + if (item.progress != null) return onOpen?.invoke(item, true) } @@ -548,7 +548,7 @@ internal class ActiveListView( */ private fun activate(item: ActiveListItem) { if (item is ActiveListGap) return - if (item.deleting) return + if (item.progress != null) return val action = onActivate if (action != null) { action(item) @@ -565,7 +565,7 @@ internal class ActiveListView( private fun primary(item: ActiveListItem) { if (item is ActiveListGap) return - if (item.deleting) return + if (item.progress != null) return val cells = activeListVisibleCells(item, true) val cell = cells.firstOrNull { it.enabled && it.primary } if (cell != null) { @@ -606,7 +606,7 @@ internal class ActiveListView( if (!list.isEnabled || filter.isNotBlank() || drag != null) return null val idx = rowAt(point) ?: return null val item = model.getElementAt(idx) - if (item is ActiveListGap || item.disabled || item.deleting) return null + if (item is ActiveListGap || item.disabled || item.progress != null) return null if (!cfg.movable(item)) return null val selected = list.isSelectedIndex(idx) if (activeListCellAt(list, idx, point, selected, menu?.takeIf { it.available(item) } != null) != null) return null @@ -746,7 +746,7 @@ internal class ActiveListView( if (!bounds.contains(point)) return false val item = model.getElementAt(idx) if (item is ActiveListGap) return false - if (item.disabled || item.deleting || !cfg.available(item)) return false + if (item.disabled || item.progress != null || !cfg.available(item)) return false val rect = activeListCellBounds(list, idx, list.isSelectedIndex(idx))[ACTIVE_LIST_MENU_CELL] ?: return false if (!rect.contains(point)) return false val popup = JBPopupFactory.getInstance().createActionGroupPopup( @@ -858,7 +858,7 @@ private data class ActiveListHeightRow( val trailing: String?, val cells: List, val disabled: Boolean, - val deleting: Boolean, + val progress: String?, ) private fun activeListHeightRow(item: ActiveListItem): ActiveListHeightRow { @@ -873,7 +873,7 @@ private fun activeListHeightRow(item: ActiveListItem): ActiveListHeightRow { item.trailing, item.cells, item.disabled, - item.deleting, + item.progress, ) } diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties index 6b0f7e387345..0d41529c9e8c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties @@ -145,11 +145,6 @@ session.dock.move=Move to Worktree session.dock.move.tooltip.empty=Move this conversation and your current local changes into a dedicated worktree for isolated follow-up work. session.dock.move.tooltip.one=Move this conversation and 1 changed file into a dedicated worktree for isolated follow-up work. session.dock.move.tooltip.other=Move this conversation and {0} changed files into a dedicated worktree for isolated follow-up work. -session.dock.progress.capturing=Capturing changes... -session.dock.progress.creating=Creating worktree... -session.dock.progress.transferring=Transferring changes... -session.dock.progress.forking=Starting session... -session.dock.move.failed.title=Failed to move to worktree diff.editor.session.title=Session Changes diff.editor.inline.title.named={0} ({1}) diff.editor.changedFiles.title=Changed files @@ -416,7 +411,11 @@ worktree.configure.base.invalid.content=Select an existing base branch before cr worktree.dialog.name.placeholder=Worktree name (optional) worktree.dialog.prompt.placeholder=Describe what you want to start working on ({0} to create) worktree.dialog.create=Create Worktree -worktree.dialog.creating=Creating… +worktree.progress.creating=Creating worktree… +worktree.progress.capturing=Capturing changes… +worktree.progress.transferring=Transferring changes… +worktree.progress.starting=Starting session… +worktree.move.failed.title=Failed to move to worktree worktree.import.pr.section=Pull Request worktree.import.pr.failed.title=Couldn''t import pull request worktree.import.branch.failed.title=Couldn''t import branch "{0}" diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index 64580e720b53..eef6909b3bde 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -13,6 +13,7 @@ import ai.kilocode.client.agentManager.worktree.WorktreeStatusService import ai.kilocode.client.agentManager.worktree.ensureWorktreeSessionEditorKind import ai.kilocode.client.agentManager.worktree.worktreeSessionParams import ai.kilocode.client.diff.KiloDiffEditorKind +import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.client.testing.FakeWorktreeRpcApi import ai.kilocode.client.testing.TestCoroutines @@ -632,7 +633,7 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals("Open #8
Click to open the pull request in your browser.", row.metrics?.prTooltip) } - fun `test worktree row hides badge while pending or deleting`() { + fun `test worktree row hides badge while in progress`() { val path = "feature/y" val activity = MutableStateFlow(mapOf( "ses_1" to SessionActivityDto(path, SessionActivityKindDto.RUNNING), @@ -647,7 +648,9 @@ class AgentManagerPanelTest : BasePlatformTestCase() { val pending = row(panel, 0) assertSame(WorktreeIcons.spinner, pending.icon) + assertEquals(KiloBundle.message("worktree.progress.creating"), pending.progress) assertEquals(emptyList(), pending.badges) + assertNull(pending.metrics) gate.complete(Unit) flush() } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt index dffd2030e5ff..10d8e04d1a10 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt @@ -7,11 +7,14 @@ import ai.kilocode.client.agentManager.worktree.PendingPrompt import ai.kilocode.client.agentManager.worktree.PendingWorktreePrompt import ai.kilocode.client.agentManager.worktree.WorktreeNameCache import ai.kilocode.client.agentManager.worktree.WorktreeNames +import ai.kilocode.client.plugin.KiloBundle import ai.kilocode.client.session.SessionActivityKind import ai.kilocode.client.testing.FakeWorktreeRpcApi import ai.kilocode.client.testing.TestCoroutines import ai.kilocode.client.testing.pumpEdt import ai.kilocode.rpc.dto.CreateWorktreeResultDto +import ai.kilocode.rpc.dto.MoveProgressDto +import ai.kilocode.rpc.dto.MoveStage import ai.kilocode.rpc.dto.RemoveWorktreeResultDto import ai.kilocode.rpc.dto.RenameWorktreeResultDto import ai.kilocode.rpc.dto.SessionActivityDto @@ -161,13 +164,13 @@ class WorktreeControllerTest : BasePlatformTestCase() { controller.remove(controller.model.getElementAt(0)) - assertTrue(controller.isDeleting(item.id)) + assertEquals(KiloBundle.message("common.deleting"), controller.progress(item.id)) assertEquals(1, controller.model.size) gate.complete(Unit) flush() - assertFalse(controller.isDeleting(item.id)) + assertNull(controller.progress(item.id)) assertEquals(0, controller.model.size) } @@ -186,7 +189,7 @@ class WorktreeControllerTest : BasePlatformTestCase() { // git rejected the removal, so the entry must remain instead of vanishing optimistically. assertEquals(1, controller.model.size) assertEquals("feature/x", controller.model.getElementAt(0).branch) - assertFalse(controller.isDeleting(item.id)) + assertNull(controller.progress(item.id)) assertEquals(1, failures.size) assertTrue(failures.first().locked) } @@ -321,6 +324,75 @@ class WorktreeControllerTest : BasePlatformTestCase() { assertEquals("/wt/pr-7", controller.model.getElementAt(0).path) } + fun `test move adds placeholder tracks progress and swaps to worktree`() { + val done = WorktreeDto("/wt/moved", "moved", "moved", "/wt/moved") + rpc.moveScript = listOf( + MoveProgressDto(MoveStage.CREATING), + MoveProgressDto(MoveStage.TRANSFERRING), + MoveProgressDto(MoveStage.FORKING), + MoveProgressDto(MoveStage.DONE, worktree = done, session = "ses_fork"), + ) + val selected = mutableListOf() + val aborts = mutableListOf>() + val events = mutableListOf>>() + val controller = controller(abort = { id, dir -> aborts += id to dir }, telemetry = { name, props -> events += name to props }) + controller.onSelect = { selected += it } + + ApplicationManager.getApplication().invokeAndWait { controller.move("ses_source", "/repo") } + val temp = controller.model.getElementAt(0) + assertTrue(controller.isPending(temp.id)) + assertEquals(KiloBundle.message("worktree.progress.capturing"), controller.progress(temp.id)) + assertEquals(temp.id, selected.single()) + flush() + + assertEquals(listOf("ses_source" to "/repo"), aborts) + assertEquals("/repo", rpc.moves.single().first) + assertEquals("ses_source", rpc.moves.single().second) + assertEquals(done, controller.model.getElementAt(0)) + assertNull(controller.progress(temp.id)) + assertEquals("ses_fork", controller.takeSession(done.id)) + assertNull(controller.takeSession(done.id)) + assertEquals(done.id, selected.last()) + assertTrue(events.any { it.first == "Continue in Worktree" && it.second["surface"] == "sidebar" }) + } + + fun `test move failure removes placeholder and reports last stage`() { + rpc.moveScript = listOf( + MoveProgressDto(MoveStage.CREATING), + MoveProgressDto(MoveStage.ERROR, error = "boom"), + ) + val failures = mutableListOf() + val events = mutableListOf>>() + val controller = controller(telemetry = { name, props -> events += name to props }) + controller.onMoveFailure = { failures += it } + + ApplicationManager.getApplication().invokeAndWait { controller.move("ses_source", "/repo") } + flush() + + assertEquals(0, controller.model.size) + assertEquals(listOf("boom"), failures) + assertTrue(events.any { it.first == "Continue in Worktree Failed" && it.second["stage"] == "CREATING" }) + } + + fun `test duplicate move for session is ignored while in flight`() { + val gate = CompletableDeferred() + rpc.moveScript = listOf(MoveProgressDto(MoveStage.DONE, worktree = WorktreeDto("/wt/moved", "moved", "moved", "/wt/moved"))) + val controller = controller(abort = { _, _ -> gate.await() }) + + ApplicationManager.getApplication().invokeAndWait { + controller.move("ses_source", "/repo") + controller.move("ses_source", "/repo") + } + flush() + + assertEquals(1, controller.model.size) + assertEquals(0, rpc.moves.size) + gate.complete(Unit) + flush() + + assertEquals(1, rpc.moves.size) + } + fun `test create stashes the prompt with its picked selection for the created worktree`() { val controller = controller() @@ -354,22 +426,22 @@ class WorktreeControllerTest : BasePlatformTestCase() { fun `test worktree row icons show only while running or waiting`() { assertSame( WorktreeIcons.spinner, - WorktreeIcons.forRow(pending = true, kind = SessionActivityKind.RUNNING), + WorktreeIcons.forRow(busy = true, kind = SessionActivityKind.RUNNING), ) assertSame( WorktreeIcons.running, - WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.RUNNING), + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.RUNNING), ) assertSame( SessionActivityKind.QUESTION.icon(), - WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.QUESTION), + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.QUESTION), ) assertSame( SessionActivityKind.PLAN.icon(), - WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.PLAN), + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.PLAN), ) - assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR)) - assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(pending = false, kind = null)) + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.ERROR)) + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(busy = false, kind = null)) } fun `test worktree icons load at the same size`() { @@ -402,10 +474,10 @@ class WorktreeControllerTest : BasePlatformTestCase() { val main = WorktreeDto("/repo", "repo", "main", "/repo", main = true) val child = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") - assertFalse(worktreeDeletable(null, pending = false)) - assertFalse(worktreeDeletable(main, pending = false)) - assertFalse(worktreeDeletable(child, pending = true)) - assertTrue(worktreeDeletable(child, pending = false)) + assertFalse(worktreeDeletable(null, busy = false)) + assertFalse(worktreeDeletable(main, busy = false)) + assertFalse(worktreeDeletable(child, busy = true)) + assertTrue(worktreeDeletable(child, busy = false)) } fun `test applyName updates the matching row so an adopted name shows live`() { @@ -468,8 +540,11 @@ class WorktreeControllerTest : BasePlatformTestCase() { assertEquals(listOf("/wt" to "Name", "/wt" to null), events) } - private fun controller(activity: MutableStateFlow> = MutableStateFlow(emptyMap())) = - WorktreeController(service, "/test", coroutines.scope, activity = activity) + private fun controller( + activity: MutableStateFlow> = MutableStateFlow(emptyMap()), + abort: suspend (String, String) -> Unit = { _, _ -> }, + telemetry: (String, Map) -> Unit = { _, _ -> }, + ) = WorktreeController(service, "/test", coroutines.scope, activity = activity, abort = abort, telemetry = telemetry) private fun flush() = coroutines.drain(::pump) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt index e0e04c05b06c..72a98c1dde63 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt @@ -12,7 +12,7 @@ import java.awt.Color class WorktreeIconsTest : BasePlatformTestCase() { fun `test running session resolves to the animated spinner`() { - assertSame(WorktreeIcons.running, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.RUNNING)) + assertSame(WorktreeIcons.running, WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.RUNNING)) } fun `test running icon is animated and sized to the row icon`() { @@ -58,36 +58,36 @@ class WorktreeIconsTest : BasePlatformTestCase() { return channels.max() - channels.min() } - fun `test pending outranks running and uses the platform spinner`() { - assertSame(WorktreeIcons.spinner, WorktreeIcons.forRow(pending = true, kind = SessionActivityKind.RUNNING)) + fun `test busy outranks running and uses the platform spinner`() { + assertSame(WorktreeIcons.spinner, WorktreeIcons.forRow(busy = true, kind = SessionActivityKind.RUNNING)) } fun `test waiting kinds resolve to the attention glyph`() { assertSame( SessionActivityKind.QUESTION.icon(), - WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.QUESTION), + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.QUESTION), ) - assertSame(SessionActivityKind.PLAN.icon(), WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.PLAN)) + assertSame(SessionActivityKind.PLAN.icon(), WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.PLAN)) } fun `test rows at rest show what the checkout is`() { - assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(pending = false)) - assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(pending = false, locked = true)) - assertSame(WorktreeIcons.local, WorktreeIcons.forRow(pending = false, current = true)) + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(busy = false)) + assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(busy = false, locked = true)) + assertSame(WorktreeIcons.local, WorktreeIcons.forRow(busy = false, current = true)) } fun `test errored session falls back to the resting glyph`() { - assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR)) + assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.ERROR)) assertSame( WorktreeIcons.local, - WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.ERROR, current = true), + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.ERROR, current = true), ) } fun `test activity outranks the resting glyph on the local row`() { assertSame( WorktreeIcons.running, - WorktreeIcons.forRow(pending = false, kind = SessionActivityKind.RUNNING, current = true), + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.RUNNING, current = true), ) } } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt index 5541e47ae457..9dbc014c804a 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanelTest.kt @@ -289,7 +289,7 @@ class WorktreeSessionEditorPanelTest : BasePlatformTestCase() { val row = row("ses_1") - assertTrue(row.deleting) + assertEquals(KiloBundle.message("common.deleting"), row.progress) } fun `test pending new session groups under today`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt index 7a179b738c80..02536953716f 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt @@ -190,6 +190,35 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertTrue(dock.isVisible) } + fun `test dock move delegates to manager without progress state`() { + val calls = mutableListOf>() + val owner = object : SessionManager { + override fun newSession() {} + override fun showHistory(back: (() -> Unit)?) {} + override fun openSession(ref: SessionRef) {} + override val supportsMoveToWorktree: Boolean get() = true + override fun moveToWorktree(sessionId: String, directory: String) { + calls += sessionId to directory + } + } + val worktree = FakeWorktreeRpcApi().apply { + branchResult = BranchStatusDto(branch = "main", availability = GhAvailability.OK) + } + ApplicationManager.getApplication() + .replaceService(KiloWorktreeService::class.java, KiloWorktreeService(scope, worktree), testRootDisposable) + rpc.history.addAll(history(1)) + ui = newUi(id = "ses_test", manager = owner) + settle() + val dock = find(ui) + assertTrue(dock.isVisible) + + dock.triggerMove() + + assertEquals(listOf("ses_test" to "/test"), calls) + assertTrue(dock.isVisible) + assertTrue(dock.moveEnabled()) + } + fun `test dock branch changes refresh on finish and revert`() { workspaceRpc.branchDiffs.clear() workspaceRpc.branchDiffs.add(DiffFileDto("src/A.kt", 2, 1)) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/history/HistoryControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/history/HistoryControllerTest.kt index 27c05f5d2951..54fad9dc42ba 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/history/HistoryControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/history/HistoryControllerTest.kt @@ -214,9 +214,9 @@ class HistoryControllerTest : BasePlatformTestCase() { val row = localHistoryRows(listOf(item), snapshot) { true }[0] - assertTrue(row.deleting) - assertTrue(row.cells.isEmpty()) - assertTrue(row.badges.isEmpty()) + assertEquals(KiloBundle.message("common.deleting"), row.progress) + assertEquals(listOf(ACTIVE_LIST_RENAME_CELL, ACTIVE_LIST_DELETE_CELL), row.cells.map { it.id }) + assertEquals(listOf(SessionActivityKind.RUNNING.label()), row.badges.map { it.text }) } fun `test history panel sync updates running badges`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt index 08fdf2c0d119..a593b03336f9 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt @@ -8,7 +8,6 @@ import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.DiffFileDto import ai.kilocode.rpc.dto.GhAvailability import ai.kilocode.rpc.dto.GhState -import ai.kilocode.rpc.dto.MoveStage import ai.kilocode.rpc.dto.WorktreePrDto import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent @@ -136,21 +135,6 @@ class BranchDockTest : BasePlatformTestCase() { assertFalse(update(ChatNewWorktreeAction(), dock).isVisible) } - fun `test move progress keeps the row while session is busy`() { - val dock = dock() - edt { - dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) - dock.setHasMessages(true) - dock.setBusy(true) - dock.setMoveProgress(MoveStage.CREATING, null) - } - assertTrue(edt { dock.isVisible }) - val p = update(ChatMoveToWorktreeAction(), dock) - assertTrue(p.isVisible) - assertFalse(p.isEnabled) - assertEquals(KiloBundle.message("session.dock.progress.creating"), p.text) - } - // ---- Move to Worktree action ---- fun `test move action visible with messages`() { @@ -191,19 +175,6 @@ class BranchDockTest : BasePlatformTestCase() { assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) } - fun `test move action shows spinner while moving`() { - val dock = dock() - edt { - dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) - dock.setHasMessages(true) - dock.setMoveProgress(MoveStage.CREATING, null) - } - val p = update(ChatMoveToWorktreeAction(), dock) - assertTrue(p.isVisible) - assertFalse(p.isEnabled) - assertEquals(KiloBundle.message("session.dock.progress.creating"), p.text) - } - fun `test move action invokes callback`() { var moved = 0 val dock = edt { BranchDock(openDiff = {}, onMove = { moved++ }) } @@ -214,6 +185,15 @@ class BranchDockTest : BasePlatformTestCase() { assertEquals(1, moved) } + fun `test move action hidden without a move host`() { + val dock = edt { BranchDock(openDiff = {}, onMove = null) } + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setHasMessages(true) + } + assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) + } + // ---- New Worktree action ---- fun `test new worktree action visible when dock active`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt index b2daca705feb..c8e9b02ac14c 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt @@ -212,6 +212,18 @@ class ActiveListSelectionTest : BasePlatformTestCase() { assertEquals("created", view.selected()?.key) } + fun `test progress row keeps cells in model but hides visible actions`() { + val item = object : ActiveListItem { + override val key = "busy" + override val title = "Busy" + override val progress = "Working..." + override val cells = listOf(ActiveListCell("open", "Open", primary = true)) + } + + assertEquals(listOf("open"), item.cells.map { it.id }) + assertEquals(emptyList(), activeListVisibleCells(item, active = true)) + } + private fun view(onSelect: () -> Unit = {}): ActiveListView { return ActiveListView("") { _, _ -> }.apply { this.onSelect = onSelect } } diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt index 848817f307a7..b3a98d6d5870 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/WorktreeDto.kt @@ -70,7 +70,6 @@ enum class MoveStage { CAPTURING, CREATING, TRANSFERRING, FORKING, DONE, ERROR } @Serializable data class MoveProgressDto( val stage: MoveStage, - val detail: String? = null, val error: String? = null, val worktree: WorktreeDto? = null, val session: String? = null, From d94f2bf1c944129054dda983ff1df3d50ddced90 Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 10:21:31 -0400 Subject: [PATCH 23/30] fix(jetbrains): address worktree move and list review findings Emit a move error for every failure path and roll back a worktree left by a failed move, so the Agent Manager row cannot stay stuck on its last stage. Fail patch capture loudly through the platform command line instead of treating a git failure as a clean tree. Keep the worktree session editor identity as the path alone and hand the forked session over through a one-shot store, so a move no longer opens a rival tab for the same worktree. Stop clicks and drags in the empty space under a short list from acting on the last row, carry the dragged row identity through the placeholder, let a failed branch status surface instead of posing as healthy git, and require a persisted session before offering Move to Worktree. Also make three worktree RPC tests void-returning: JUnit silently skips @Test methods that return a value, so they never ran. --- .changeset/worktree-move-reliability.md | 5 + .../backend/rpc/KiloWorktreeRpcApiImpl.kt | 46 +++++--- .../kilocode/backend/rpc/WorktreeTransfer.kt | 103 +++++++++++------- .../backend/rpc/KiloWorktreeRpcApiImplTest.kt | 43 +++++++- .../client/agentManager/AgentManagerPanel.kt | 2 +- .../worktree/KiloWorktreeService.kt | 13 ++- .../worktree/PendingWorktreeSession.kt | 29 +++++ .../worktree/WorktreeController.kt | 7 +- .../worktree/WorktreeSessionEditorKind.kt | 14 +-- .../ai/kilocode/client/session/SessionUi.kt | 11 +- .../client/session/ui/header/BranchDock.kt | 15 ++- .../client/ui/list/ActiveListReorder.kt | 3 + .../kilocode/client/ui/list/ActiveListView.kt | 20 +++- .../agentManager/WorktreeControllerTest.kt | 9 +- .../WorktreeSessionEditorKindTest.kt | 13 +++ .../client/session/SessionUiLayoutTest.kt | 40 +++++++ .../session/ui/header/BranchDockTest.kt | 20 +++- .../client/testing/FakeWorktreeRpcApi.kt | 3 + .../client/ui/list/ActiveListReorderTest.kt | 74 ++++++++++++- 19 files changed, 386 insertions(+), 84 deletions(-) create mode 100644 .changeset/worktree-move-reliability.md create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/PendingWorktreeSession.kt diff --git a/.changeset/worktree-move-reliability.md b/.changeset/worktree-move-reliability.md new file mode 100644 index 000000000000..93f41a539389 --- /dev/null +++ b/.changeset/worktree-move-reliability.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Report failures when moving a chat into a worktree instead of leaving the row stuck, clean up worktrees left by a failed move, and stop clicks in empty list space from selecting the last row. diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt index c3d78a47cf47..24179a828900 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt @@ -32,6 +32,7 @@ import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.WindowManager import com.intellij.util.concurrency.annotations.RequiresEdt +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope @@ -206,44 +207,63 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi { dto } + /** + * Every failure path — including a throw from capture, worktree creation bookkeeping, or the + * fork — emits [MoveStage.ERROR] and rolls back a worktree that was already created. The + * frontend collector has no error handling of its own, so a silent flow completion would leave + * the Agent Manager row stuck on its last stage forever. + */ override suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow = flow { val base = Path.of(directory).normalize() LOG.info("worktree move requested: dir=$base session=$sessionId branch=$branch") - emit(MoveProgressDto(MoveStage.CAPTURING)) - val snapshot = withContext(Dispatchers.IO) { WorktreeTransfer.capture(base) } + // Both survive the try so `finally` can drop temp patches and the failure paths can drop a + // worktree that was already created. + var snapshot: WorktreeTransfer.Snapshot? = null + var leftover: WorktreeDto? = null try { + emit(MoveProgressDto(MoveStage.CAPTURING)) + val captured = withContext(Dispatchers.IO) { WorktreeTransfer.capture(base) }.also { snapshot = it } emit(MoveProgressDto(MoveStage.CREATING)) val created = withContext(Dispatchers.IO) { - addWorktree(base, branch.trim(), existing = false, baseRef = snapshot.head) + addWorktree(base, branch.trim(), existing = false, baseRef = captured.head) } val worktree = created.worktree ?: run { emit(MoveProgressDto(MoveStage.ERROR, error = created.error ?: "Failed to create worktree")) return@flow } + leftover = worktree val target = Path.of(worktree.path).normalize() emit(MoveProgressDto(MoveStage.TRANSFERRING)) - val applied = withContext(Dispatchers.IO) { WorktreeTransfer.apply(snapshot, base, target) } + val applied = withContext(Dispatchers.IO) { WorktreeTransfer.apply(captured, base, target) } if (!applied.ok) { - LOG.warn("worktree move: rolling back ${worktree.path} after transfer failure") - remove(directory, worktree.path, branch, force = true) + leftover = null + rollback(directory, worktree, branch, "transfer failure") emit(MoveProgressDto(MoveStage.ERROR, error = applied.error ?: "Failed to apply changes to worktree")) return@flow } emit(MoveProgressDto(MoveStage.FORKING)) - val forked = runCatching { - withContext(Dispatchers.IO) { service().sessions.fork(sessionId, worktree.path) } - }.getOrElse { err -> - LOG.warn("worktree move: fork failed session=$sessionId", err) - emit(MoveProgressDto(MoveStage.ERROR, error = err.message ?: "Failed to fork session")) - return@flow - } + val forked = withContext(Dispatchers.IO) { service().sessions.fork(sessionId, worktree.path) } + leftover = null LOG.info("worktree move done: worktree=${worktree.path} session=${forked.id}") emit(MoveProgressDto(MoveStage.DONE, worktree = worktree, session = forked.id)) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + LOG.warn("worktree move failed: dir=$base session=$sessionId branch=$branch", e) + leftover?.let { rollback(directory, it, branch, "move failure") } + emit(MoveProgressDto(MoveStage.ERROR, error = e.message ?: "Failed to move session to a worktree")) } finally { withContext(Dispatchers.IO) { WorktreeTransfer.cleanup(snapshot) } } } + /** Drops a worktree created earlier in a failed move so a retry is not blocked by leftovers. */ + private suspend fun rollback(directory: String, worktree: WorktreeDto, branch: String, reason: String) { + LOG.warn("worktree move: rolling back ${worktree.path} after $reason") + runCatching { remove(directory, worktree.path, branch, force = true) } + .onFailure { err -> LOG.warn("worktree move: rollback of ${worktree.path} failed", err) } + } + /** Detects a linked (non-primary) worktree: its git-dir differs from the shared common git-dir. */ private fun isLinkedWorktree(root: Path): Boolean { val res = runGit(root, "rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir") diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt index 84b5c17dd7e3..d7b2fa39c32e 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt @@ -6,6 +6,7 @@ import com.intellij.execution.process.CapturingProcessHandler import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path +import java.util.concurrent.TimeUnit import kotlin.io.path.fileSize /** @@ -14,8 +15,11 @@ import kotlin.io.path.fileSize * modifying the source working tree. * * Ported from `packages/kilo-vscode/src/agent-manager/git-transfer.ts`. Patches are captured to temp - * files with [ProcessBuilder.redirectOutput] rather than decoded to strings: `CapturingProcessHandler` - * decodes stdout with a charset and would corrupt `--binary` patches. + * files with a redirected stdout rather than decoded to strings: `CapturingProcessHandler` decodes + * stdout with a charset and would corrupt `--binary` patches. + * + * [capture] throws when git itself fails. A failure must never look like a clean tree, or the move + * would report success while leaving the user's tracked edits behind. */ internal object WorktreeTransfer { private val LOG = KiloLog.create(WorktreeTransfer::class.java) @@ -39,29 +43,39 @@ internal object WorktreeTransfer { */ fun capture(root: Path): Snapshot { val branch = git(root, "branch", "--show-current").stdout.trim() - val head = git(root, "rev-parse", "HEAD").stdout.trim() - val unstaged = capturePatch(root, "diff", "--binary") - val staged = capturePatch(root, "diff", "--cached", "--binary") - val untracked = git(root, "ls-files", "--others", "--exclude-standard").stdout - .lineSequence() - .map { it.trim() } - .filter { it.isNotEmpty() } - .filter { rel -> - val full = root.resolve(rel).normalize() - if (!full.startsWith(root)) { - LOG.warn("worktree move: skipping untracked file outside root: $rel") - return@filter false - } - val size = runCatching { full.fileSize() }.getOrDefault(0L) - if (size > MAX_FILE) { - LOG.info("worktree move: skipping untracked file $rel: $size bytes exceeds ${MAX_FILE} limit") - false - } else { - true + val rev = git(root, "rev-parse", "HEAD") + if (!rev.ok) error("git rev-parse HEAD failed: ${rev.stderr.trim()}") + val head = rev.stdout.trim().ifEmpty { error("git rev-parse HEAD returned no commit") } + val temps = mutableListOf() + try { + val unstaged = capturePatch(root, "diff", "--binary")?.also { temps.add(it) } + val staged = capturePatch(root, "diff", "--cached", "--binary")?.also { temps.add(it) } + val listed = git(root, "ls-files", "--others", "--exclude-standard") + if (!listed.ok) error("git ls-files failed: ${listed.stderr.trim()}") + val untracked = listed.stdout + .lineSequence() + .map { it.trim() } + .filter { it.isNotEmpty() } + .filter { rel -> + val full = root.resolve(rel).normalize() + if (!full.startsWith(root)) { + LOG.warn("worktree move: skipping untracked file outside root: $rel") + return@filter false + } + val size = runCatching { full.fileSize() }.getOrDefault(0L) + if (size > MAX_FILE) { + LOG.info("worktree move: skipping untracked file $rel: $size bytes exceeds ${MAX_FILE} limit") + false + } else { + true + } } - } - .toList() - return Snapshot(branch, head, staged, unstaged, untracked) + .toList() + return Snapshot(branch, head, staged, unstaged, untracked) + } catch (e: Exception) { + temps.forEach { Files.deleteIfExists(it) } + throw e + } } /** @@ -103,31 +117,40 @@ internal object WorktreeTransfer { listOfNotNull(snapshot.staged, snapshot.unstaged).forEach { Files.deleteIfExists(it) } } - /** Runs `git diff` capturing raw bytes to a temp file; returns null when clean or on failure. */ + /** + * Runs `git diff` capturing raw bytes to a temp file. Returns null only for a genuinely empty + * diff; any failure throws so the move reports an error instead of silently transferring a + * subset of the user's work. + * + * Goes through [GeneralCommandLine.toProcessBuilder] rather than a bare [ProcessBuilder] so git + * is resolved with the same PATH as the rest of this class — a Toolbox- or Dock-launched IDE + * inherits a minimal environment where a bare `git` can be missing. Output is still redirected + * to a file because decoding stdout would corrupt `--binary` patches. + */ private fun capturePatch(root: Path, vararg args: String): Path? { val file = Files.createTempFile("kilo-worktree-patch", ".diff") - return try { - val proc = ProcessBuilder(listOf("git") + args) - .directory(root.toFile()) + val label = "git ${args.joinToString(" ")}" + try { + val cmd = GeneralCommandLine(listOf("git") + args).withWorkDirectory(root.toFile()) + val proc = cmd.toProcessBuilder() .redirectOutput(file.toFile()) .redirectErrorStream(false) .start() - val done = proc.waitFor(TIMEOUT.toLong(), java.util.concurrent.TimeUnit.MILLISECONDS) - if (!done) { + // stdout goes to the file, so draining stderr first cannot deadlock. + val err = proc.errorStream.use { it.readBytes().toString(StandardCharsets.UTF_8) } + if (!proc.waitFor(TIMEOUT.toLong(), TimeUnit.MILLISECONDS)) { proc.destroyForcibly() - Files.deleteIfExists(file) - return null - } - if (proc.exitValue() != 0 || file.fileSize() == 0L) { - Files.deleteIfExists(file) - null - } else { - file + error("$label timed out after ${TIMEOUT}ms") } + val exit = proc.exitValue() + if (exit != 0) error("$label failed (exit $exit): ${err.trim()}") + if (file.fileSize() > 0L) return file + Files.deleteIfExists(file) + return null } catch (e: Exception) { - LOG.warn("worktree move: capture patch failed: ${e.message}", e) Files.deleteIfExists(file) - null + LOG.warn("worktree move: $label failed: ${e.message}", e) + throw e } } diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt index ce5768390f45..7b51982febb3 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt @@ -3,15 +3,18 @@ package ai.kilocode.backend.rpc import ai.kilocode.rpc.dto.CreateWorktreeRequestDto import ai.kilocode.rpc.dto.GhAvailability import ai.kilocode.rpc.dto.GhState +import ai.kilocode.rpc.dto.MoveStage import ai.kilocode.rpc.dto.WorktreeDto import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler +import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import java.nio.file.Files import java.nio.file.Path import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFails import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -353,7 +356,7 @@ class KiloWorktreeRpcApiImplTest { val result = api.remove(repo.toString(), repo.resolve("does-not-exist").toString(), null) assertFalse(result.ok, "remove of a missing worktree should not report success") - assertNotNull(result.error, "failure should carry an error message") + assertTrue(result.error != null, "failure should carry an error message") } @Test @@ -409,7 +412,7 @@ class KiloWorktreeRpcApiImplTest { val result = api.create(repo.toString(), CreateWorktreeRequestDto("no-such-branch", existingBranch = true)) assertNull(result.worktree, "unknown branch should not create a worktree") - assertNotNull(result.error) + assertTrue(result.error != null, "failure should carry an error message") } @Test @@ -510,6 +513,42 @@ class KiloWorktreeRpcApiImplTest { WorktreeTransfer.cleanup(snapshot) } + @Test + fun `capture fails instead of reporting a clean tree when git cannot run`() { + // No git repository: a failed capture must throw rather than look like "nothing to move". + val err = assertFails { WorktreeTransfer.capture(repo) } + + assertTrue(err.message.orEmpty().isNotBlank(), "capture failure should explain itself") + } + + @Test + fun `moveToWorktree emits ERROR when capture fails`() = runBlocking { + val events = api.moveToWorktree(repo.toString(), "ses_1", "feature/x").toList() + + assertEquals(MoveStage.CAPTURING, events.first().stage) + val last = events.last() + assertEquals(MoveStage.ERROR, last.stage) + assertTrue(last.error != null, "the error event should explain the failure") + } + + @Test + fun `moveToWorktree rolls back the created worktree when a later stage throws`() = runBlocking { + initRepo() + Files.writeString(repo.resolve("untracked.txt"), "brand new\n") + + // The fork resolves a project-level service that no plain unit test provides, so this move + // throws after the worktree exists — exactly the case that used to end the flow silently. + val events = api.moveToWorktree(repo.toString(), "ses_1", "feature/x").toList() + + assertEquals(MoveStage.ERROR, events.last().stage) + assertTrue(events.map { it.stage }.containsAll(listOf(MoveStage.CREATING, MoveStage.TRANSFERRING))) + assertFalse( + Files.exists(repo.resolve(".kilo").resolve("worktrees").resolve("feature-x")), + "a failed move must not leave its worktree behind", + ) + assertTrue(api.list(repo.toString()).worktrees.none { it.branch == "feature/x" }, "git must not track the worktree") + } + private fun statusOf(dir: Path): String { val cmd = GeneralCommandLine(listOf("git", "status", "--porcelain")).withWorkDirectory(dir.toFile()) return CapturingProcessHandler(cmd).runProcess(30_000).stdout diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 6bcd55ff2699..68f8e77e0252 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -208,7 +208,7 @@ class AgentManagerPanel( private fun open(item: WorktreeDto, focus: Boolean) { val target = project ?: return if (controller.progress(item.id) != null) return - openWorktreeSession(target, item, controller.takeSession(item.id), focus) + openWorktreeSession(target, item, focus) } private fun close(item: WorktreeDto) { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt index 832dd8d12512..9a1f4fca5c4c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt @@ -100,12 +100,13 @@ class KiloWorktreeService internal constructor( WorktreePrListDto() } - suspend fun branchStatus(directory: String): BranchStatusDto = try { - call { branchStatus(directory) } - } catch (e: Exception) { - LOG.warn("worktree branch status failed for $directory", e) - BranchStatusDto() - } + /** + * Branch/PR status for one directory, or a thrown failure. Deliberately not swallowed: an empty + * [BranchStatusDto] defaults to [GhAvailability.OK], which the chat dock reads as healthy git and + * would offer worktree actions against a directory whose real state is unknown. Callers decide + * what an unknown status means. + */ + suspend fun branchStatus(directory: String): BranchStatusDto = call { branchStatus(directory) } /** * Long-lived move flow. Routed through [durable] (via [call]) so it survives reconnects and diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/PendingWorktreeSession.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/PendingWorktreeSession.kt new file mode 100644 index 000000000000..3925583a6426 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/PendingWorktreeSession.kt @@ -0,0 +1,29 @@ +package ai.kilocode.client.agentManager.worktree + +import com.intellij.openapi.components.Service +import com.intellij.util.concurrency.annotations.RequiresEdt + +/** + * One-shot handoff of a session id to a freshly-opened worktree session editor, keyed by worktree + * path. Used by "Move to Worktree" so the editor shows the forked conversation instead of starting a + * new one. + * + * The session deliberately does not travel in the editor's VFS params: [WorktreeSessionEditorKind] + * identity is the worktree path alone, so open / close / rename / delete all address the same tab. + * Adding a second param would create a rival identity and leave duplicate tabs behind. Mirrors + * [PendingWorktreePrompt]. + */ +@Service(Service.Level.APP) +class PendingWorktreeSession { + private val sessions = HashMap() + + @RequiresEdt + fun put(path: String, session: String) { + if (session.isBlank()) return + sessions[normalizeWorktreePath(path)] = session + } + + /** Returns and clears the queued session for [path], or null when none is queued. */ + @RequiresEdt + fun take(path: String): String? = sessions.remove(normalizeWorktreePath(path)) +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt index 1e1408342f46..f96a7fb7c414 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt @@ -36,7 +36,6 @@ class WorktreeController( private val pending = LinkedHashMap() private val tasks = LinkedHashMap() private val moves = LinkedHashSet() - private val sessions = LinkedHashMap() var onSelect: ((String) -> Unit)? = null var onCreateFailure: ((String?) -> Unit)? = null var onMoveFailure: ((String?) -> Unit)? = null @@ -80,8 +79,6 @@ class WorktreeController( fun progress(id: String): String? = tasks[id] - fun takeSession(id: String): String? = sessions.remove(id) - fun kind(path: String): SessionActivityKind? = kinds[normalizeWorktreePath(path)] fun reload() { @@ -243,7 +240,9 @@ class WorktreeController( val idx = model.getElementIndex(temp) if (idx >= 0) model.setElementAt(worktree, idx) else model.add(worktree) cache().put(worktree) - event.session?.let { sessions[worktree.id] = it } + // Queue the forked session for the editor the selection is about to + // open; the tab's identity stays the worktree path alone. + event.session?.let { service().put(worktree.path, it) } onSelect?.invoke(worktree.id) telemetry("Continue in Worktree", mapOf("surface" to "sidebar")) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt index 569bbc7ae2e5..ee3777c1f63c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorKind.kt @@ -39,7 +39,9 @@ object WorktreeSessionEditorKind : KiloEditorKind { @RequiresEdt override fun createContent(project: Project, file: KiloVirtualFile, parent: Disposable): JComponent { val path = file.path.params[PATH]?.takeIf { it.isNotBlank() } ?: return BorderLayoutPanel() - val session = file.path.params[SESSION]?.takeIf { it.isNotBlank() } + // A move queues its forked session here rather than in the params, which are this editor's + // identity: a second param would open a rival tab for the same worktree. + val session = service().take(path) val worktree = service().workspace(path) val cs = service().scope() Disposer.register(parent) { cs.cancel() } @@ -49,7 +51,6 @@ object WorktreeSessionEditorKind : KiloEditorKind { } private const val PATH = "path" - private const val SESSION = "session" } fun ensureWorktreeSessionEditorKind() { @@ -60,11 +61,10 @@ internal fun unregisterWorktreeSessionEditorKind() { service().unregister(WorktreeSessionEditorKind.ID) } -internal fun worktreeSessionParams(item: WorktreeDto, session: String? = null): Map = linkedMapOf( - "path" to item.path, -).apply { session?.takeIf { it.isNotBlank() }?.let { put("session", it) } } +/** Editor identity for a worktree session tab: the worktree path and nothing else. */ +internal fun worktreeSessionParams(item: WorktreeDto): Map = mapOf("path" to item.path) -internal fun openWorktreeSession(project: Project, worktree: WorktreeDto, session: String? = null, focus: Boolean = true) { +internal fun openWorktreeSession(project: Project, worktree: WorktreeDto, focus: Boolean = true) { ensureWorktreeSessionEditorKind() - project.service().open(WorktreeSessionEditorKind.ID, worktreeSessionParams(worktree, session), focus) + project.service().open(WorktreeSessionEditorKind.ID, worktreeSessionParams(worktree), focus) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt index 7641bddc708e..5ad144c4ed3d 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt @@ -245,7 +245,7 @@ class SessionUi( bindMigration() onStateChanged(controller.model.state) dock?.let { - it.setHasMessages(controller.model.messages().isNotEmpty()) + syncDock() refreshBranchChanges() refreshBranch() } @@ -644,7 +644,7 @@ class SessionUi( is SessionModelEvent.MessageAdded, is SessionModelEvent.MessageRemoved, is SessionModelEvent.HistoryLoaded, - is SessionModelEvent.Cleared -> syncDockMessages() + is SessionModelEvent.Cleared -> syncDock() is SessionModelEvent.QueueChanged -> Unit @@ -665,8 +665,10 @@ class SessionUi( } @RequiresEdt - private fun syncDockMessages() { - dock?.setHasMessages(controller.model.messages().isNotEmpty()) + private fun syncDock() { + val dock = dock ?: return + dock.setHasMessages(controller.model.messages().isNotEmpty()) + dock.setHasSession(controller.id != null) } @RequiresEdt @@ -1114,6 +1116,7 @@ class SessionUi( } private fun onSessionUpdated() { + syncDock() manager?.activityChanged() } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt index 20f37ce60e00..eba539a00b7b 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt @@ -58,6 +58,7 @@ internal class BranchDock( private var files = emptyList() private var branch: BranchStatusDto? = null private var hasMessages = false + private var hasSession = false private var busy = false init { @@ -110,11 +111,23 @@ internal class BranchDock( sync() } + /** + * Whether the chat already has a persisted session. A brand-new session has no id until its + * first prompt, and there is nothing to move until then — even in a repository with local + * changes, which would otherwise activate the dock. + */ + @RequiresEdt + fun setHasSession(value: Boolean) { + if (hasSession == value) return + hasSession = value + sync() + } + // ---- state read by the toolbar actions ---- fun newWorktreeEnabled(): Boolean = onNewWorktree != null && dockActive() - fun moveEnabled(): Boolean = onMove != null && dockActive() + fun moveEnabled(): Boolean = onMove != null && hasSession && dockActive() fun changeCount(): Int = files.size diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt index 719331ffb893..02cd56242d3e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt @@ -27,6 +27,9 @@ internal data class ActiveListGap( val height: Int, ) : ActiveListItem { override val key: String get() = source.key + // Carry the dragged row's identity so a refresh mid-drag reselects the placeholder instead of + // dropping the selection: rows whose identity differs from their key (worktrees) would not match. + override val identity: Any get() = source.identity override val title: String get() = "" override val section: String? get() = source.section override val disabled: Boolean get() = true diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt index 79f3dfa42dd9..0d04cb9a02d2 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListView.kt @@ -655,7 +655,7 @@ internal class ActiveListView( } val run = activeListSectionRun(base, from) if (run.isEmpty()) return - val idx = rowAt(point) ?: state.index + val idx = nearestRow(point) ?: state.index val next = idx.coerceIn(run.first, run.last) if (state.index == next && current != null) return drag = state.copy(index = next) @@ -792,11 +792,27 @@ internal class ActiveListView( return e.isShiftDown || e.isMetaDown || e.isControlDown } + /** + * The row containing [point], or null when it lands outside every cell. A short list in a + * viewport-tracking surface leaves empty space under the last row, and a click or drag there + * must not act on that row. + */ private fun rowAt(point: Point): Int? { val idx = list.locationToIndex(point) if (idx < 0) return null val bounds = list.getCellBounds(idx, idx) ?: return null - if (bounds.contains(point)) return idx + return idx.takeIf { bounds.contains(point) } + } + + /** + * Like [rowAt], but clamps to the nearest row so dragging above the first or below the last row + * still resolves a drop slot. Only the drag-over path wants this. + */ + private fun nearestRow(point: Point): Int? { + rowAt(point)?.let { return it } + val idx = list.locationToIndex(point) + if (idx < 0) return null + val bounds = list.getCellBounds(idx, idx) ?: return null if (point.y < bounds.y) return 0 return (model.size - 1).takeIf { it >= 0 } } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt index 10d8e04d1a10..a6060386b6b0 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt @@ -5,6 +5,7 @@ import ai.kilocode.client.agentManager.worktree.KiloWorktreeService import ai.kilocode.client.agentManager.worktree.WorktreeController import ai.kilocode.client.agentManager.worktree.PendingPrompt import ai.kilocode.client.agentManager.worktree.PendingWorktreePrompt +import ai.kilocode.client.agentManager.worktree.PendingWorktreeSession import ai.kilocode.client.agentManager.worktree.WorktreeNameCache import ai.kilocode.client.agentManager.worktree.WorktreeNames import ai.kilocode.client.plugin.KiloBundle @@ -350,8 +351,12 @@ class WorktreeControllerTest : BasePlatformTestCase() { assertEquals("ses_source", rpc.moves.single().second) assertEquals(done, controller.model.getElementAt(0)) assertNull(controller.progress(temp.id)) - assertEquals("ses_fork", controller.takeSession(done.id)) - assertNull(controller.takeSession(done.id)) + // The forked session is queued for the editor the selection opens, keyed by worktree path, + // so the tab identity stays the path alone. One-shot: a second open starts a new session. + ApplicationManager.getApplication().invokeAndWait { + assertEquals("ses_fork", service().take(done.path)) + assertNull(service().take(done.path)) + } assertEquals(done.id, selected.last()) assertTrue(events.any { it.first == "Continue in Worktree" && it.second["surface"] == "sidebar" }) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeSessionEditorKindTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeSessionEditorKindTest.kt index 1f6bbf7ec338..90c429667ed4 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeSessionEditorKindTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeSessionEditorKindTest.kt @@ -1,5 +1,6 @@ package ai.kilocode.client.agentManager +import ai.kilocode.client.agentManager.worktree.PendingWorktreeSession import ai.kilocode.client.agentManager.worktree.WorktreeSessionEditorKind import ai.kilocode.client.agentManager.worktree.WorktreeSessionFileType import ai.kilocode.client.agentManager.worktree.WorktreeNameCache @@ -33,6 +34,18 @@ class WorktreeSessionEditorKindTest : BasePlatformTestCase() { assertEquals(mapOf("path" to item.path), params) } + fun `test a moved session is queued out of band so the tab identity stays the path`() { + val item = WorktreeDto("/repo/.kilo/worktrees/feature-x", "feature-x", "feature/x", "/repo/.kilo/worktrees/feature-x") + service().put(item.path, "ses_fork") + + // The queued session must not leak into the editor identity, or Agent Manager's path-only + // open/close/rename would address a different file than the tab a move produced. + assertEquals(mapOf("path" to item.path), worktreeSessionParams(item)) + // Keyed by normalized path, and consumed once so a later open starts a fresh session. + assertEquals("ses_fork", service().take(item.path + "/")) + assertNull(service().take(item.path)) + } + fun `test worktree session kind creates a custom virtual file type`() { ensureWorktreeSessionEditorKind() val fs = KiloVirtualFileSystem.getInstance() diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt index 02536953716f..7cd31a1406e2 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt @@ -219,6 +219,46 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertTrue(dock.moveEnabled()) } + fun `test dock move stays disabled for a new session with local changes`() { + val owner = object : SessionManager { + override fun newSession() {} + override fun showHistory(back: (() -> Unit)?) {} + override fun openSession(ref: SessionRef) {} + override val supportsMoveToWorktree: Boolean get() = true + } + val worktree = FakeWorktreeRpcApi().apply { + branchResult = BranchStatusDto(branch = "main", availability = GhAvailability.OK) + } + ApplicationManager.getApplication() + .replaceService(KiloWorktreeService::class.java, KiloWorktreeService(scope, worktree), testRootDisposable) + workspaceRpc.branchDiffs.add(DiffFileDto("src/A.kt", 2, 1)) + // A brand-new sidebar session: no id until the first prompt, so nothing exists to move even + // though the local changes keep the dock on screen. + ui = newUi(manager = owner) + settle() + val dock = find(ui) + + assertTrue(dock.isVisible) + assertFalse(dock.moveEnabled()) + + showMessages() + + assertTrue(dock.moveEnabled()) + } + + fun `test a failed branch status leaves the dock inactive instead of assuming healthy git`() { + val worktree = FakeWorktreeRpcApi().apply { branchThrows = IllegalStateException("backend down") } + ApplicationManager.getApplication() + .replaceService(KiloWorktreeService::class.java, KiloWorktreeService(scope, worktree), testRootDisposable) + rpc.history.addAll(history(1)) + ui = newUi(id = "ses_test") + settle() + + // An empty status DTO would default to GhAvailability.OK and offer worktree actions against + // a directory whose git state is unknown, so a failure must leave the dock untouched. + assertFalse(find(ui).isVisible) + } + fun `test dock branch changes refresh on finish and revert`() { workspaceRpc.branchDiffs.clear() workspaceRpc.branchDiffs.add(DiffFileDto("src/A.kt", 2, 1)) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt index a593b03336f9..15e05df843a3 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt @@ -142,6 +142,7 @@ class BranchDockTest : BasePlatformTestCase() { edt { dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) dock.setHasMessages(true) + dock.setHasSession(true) } val p = update(ChatMoveToWorktreeAction(), dock) assertTrue(p.isVisible) @@ -154,10 +155,26 @@ class BranchDockTest : BasePlatformTestCase() { edt { dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) dock.setChanges(listOf(DiffFileDto("src/A.kt", 2, 1))) + dock.setHasSession(true) } assertTrue(update(ChatMoveToWorktreeAction(), dock).isVisible) } + fun `test move action hidden until the chat has a session`() { + val dock = dock() + edt { + dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) + dock.setChanges(listOf(DiffFileDto("src/A.kt", 2, 1))) + } + // A new sidebar session has no id until its first prompt, so there is nothing to move even + // though the local changes activate the dock. + assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) + + edt { dock.setHasSession(true) } + + assertTrue(update(ChatMoveToWorktreeAction(), dock).isVisible) + } + fun `test move action hidden with nothing to move`() { val dock = dock() edt { @@ -177,7 +194,7 @@ class BranchDockTest : BasePlatformTestCase() { fun `test move action invokes callback`() { var moved = 0 - val dock = edt { BranchDock(openDiff = {}, onMove = { moved++ }) } + val dock = edt { BranchDock(openDiff = {}, onMove = { moved++ }).also { it.setHasSession(true) } } val action = ChatMoveToWorktreeAction() val event = event(action, dock) edt { ActionUtil.updateAction(action, event) } @@ -190,6 +207,7 @@ class BranchDockTest : BasePlatformTestCase() { edt { dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) dock.setHasMessages(true) + dock.setHasSession(true) } assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt index b4fd679f5213..b9e85c2c8501 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt @@ -28,6 +28,8 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { var ghResult = GhAvailability.OK var prResult = WorktreePrListDto() var branchResult = BranchStatusDto() + /** When set, [branchStatus] throws it instead of answering. */ + var branchThrows: Exception? = null var currentBranch: String? = null val moves = CopyOnWriteArrayList>() /** Progress events emitted by [moveToWorktree], in order. */ @@ -95,6 +97,7 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { override suspend fun branchStatus(directory: String): BranchStatusDto { assertNotEdt("branchStatus") + branchThrows?.let { throw it } return branchResult } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt index a04269cb12fe..b52a388b2d14 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt @@ -1,10 +1,13 @@ package ai.kilocode.client.ui.list +import ai.kilocode.client.testing.fire import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.ui.UIUtil import java.awt.Image import java.awt.Point import java.awt.Rectangle +import java.awt.event.InputEvent +import java.awt.event.MouseEvent import java.awt.image.BufferedImage class ActiveListReorderTest : BasePlatformTestCase() { @@ -189,6 +192,74 @@ class ActiveListReorderTest : BasePlatformTestCase() { assertEquals(plain.getHeight(null), header.getHeight(null)) } + fun `test empty space under the last row is neither pickable nor draggable`() { + val view = view(mutableListOf()) + view.update(sectioned()) + layout(view) + val point = below(view) + + // A short list in a viewport-tracking surface leaves empty space; it belongs to no row. + assertNull(view.pickable(point)) + assertNull(view.dragImage(point)) + } + + fun `test clicking empty space under the last row leaves the selection alone`() { + val view = view(mutableListOf()) + view.update(sectioned()) + layout(view) + + click(view, below(view)) + + assertNull(view.selected()) + } + + fun `test dragging below the last row still targets the last slot`() { + val view = view(mutableListOf()) + view.update(sectioned()) + layout(view) + + view.over("a", below(view)) + + assertEquals(listOf("cur", "b", "c", "a"), display(view).map { it.key }) + } + + fun `test the gap carries the dragged row identity so a refresh keeps the selection`() { + val rows = listOf(row("cur", null), row("wt1", "wt", "worktree:/a"), row("wt2", "wt", "worktree:/b")) + val view = view(mutableListOf()) + view.update(rows) + layout(view) + assertTrue(view.select("wt2")) + + view.over("wt2", center(view, 1)) + // A stats/activity poll refreshing the same rows mid-drag restores by identity, which the + // placeholder must answer for — otherwise the selection is dropped while the drag runs. + view.update(rows) + + assertEquals("wt2", view.selected()?.key) + } + + /** A point in the empty space below the last row, which a tool-window list keeps visible. */ + private fun below(view: ActiveListView): Point { + val last = view.list.model.size - 1 + val bounds = view.list.getCellBounds(last, last) ?: error("no bounds for $last") + return Point(bounds.x + 8, bounds.y + bounds.height + 20) + } + + private fun click(view: ActiveListView, point: Point) { + val press = MouseEvent( + view.list, + MouseEvent.MOUSE_PRESSED, + System.currentTimeMillis(), + InputEvent.BUTTON1_DOWN_MASK, + point.x, + point.y, + 1, + false, + MouseEvent.BUTTON1, + ) + fire(view.list, press) + } + private fun view( moves: MutableList, cfg: ActiveListConfig = ActiveListConfig.Equal, @@ -239,8 +310,9 @@ class ActiveListReorderTest : BasePlatformTestCase() { private fun rows(vararg keys: String): List = keys.map { row(it, "wt") } - private fun row(key: String, section: String?): ActiveListItem = object : ActiveListItem { + private fun row(key: String, section: String?, identity: Any = key): ActiveListItem = object : ActiveListItem { override val key = key + override val identity = identity override val title = key override val section = section } From 98928aeed0c10cfe82ca2011bc49b437008bb62c Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 12:40:15 -0400 Subject: [PATCH 24/30] fix(jetbrains): enable worktree moves from local changes --- ...ains-chat-dock-move-and-worktree-dialog.md | 5 ++ .../backend/rpc/KiloWorktreeRpcApiImpl.kt | 19 ++++--- .../backend/rpc/KiloWorktreeRpcApiImplTest.kt | 23 +++++++++ .../kilocode/client/KiloToolWindowFactory.kt | 8 +-- .../actions/ChatMoveToWorktreeAction.kt | 15 +++--- .../client/agentManager/AgentManagerPanel.kt | 38 +++++++++----- .../worktree/KiloWorktreeService.kt | 2 +- .../worktree/NewWorktreeDialog.kt | 33 +++++++++--- .../worktree/WorktreeController.kt | 26 ++++++---- .../kilocode/client/session/SessionManager.kt | 2 +- .../client/session/SessionSidePanelManager.kt | 4 +- .../ai/kilocode/client/session/SessionUi.kt | 3 +- .../client/session/ui/header/BranchDock.kt | 15 +++--- .../resources/messages/KiloBundle.properties | 2 + .../agentManager/AgentManagerPanelTest.kt | 51 +++++++++++++++++++ .../agentManager/WorktreeControllerTest.kt | 48 ++++++++++++++++- .../worktree/NewWorktreeDialogTest.kt | 34 ++++++------- .../client/session/SessionUiLayoutTest.kt | 20 +++++--- .../session/ui/header/BranchDockTest.kt | 25 ++++----- .../client/testing/FakeWorktreeRpcApi.kt | 4 +- .../ai/kilocode/rpc/KiloWorktreeRpcApi.kt | 7 +-- 21 files changed, 278 insertions(+), 106 deletions(-) create mode 100644 .changeset/jetbrains-chat-dock-move-and-worktree-dialog.md diff --git a/.changeset/jetbrains-chat-dock-move-and-worktree-dialog.md b/.changeset/jetbrains-chat-dock-move-and-worktree-dialog.md new file mode 100644 index 000000000000..6e59b5905f4b --- /dev/null +++ b/.changeset/jetbrains-chat-dock-move-and-worktree-dialog.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Offer Move to Worktree in the chat toolbar whenever the repository has local changes, even before the chat has a session — the worktree gets your changes and starts its own session. New Worktree from the chat toolbar now opens its dialog first and only switches to Agents once you confirm, and the dialog opens narrower. diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt index 24179a828900..dc033a032b64 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt @@ -209,11 +209,11 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi { /** * Every failure path — including a throw from capture, worktree creation bookkeeping, or the - * fork — emits [MoveStage.ERROR] and rolls back a worktree that was already created. The - * frontend collector has no error handling of its own, so a silent flow completion would leave - * the Agent Manager row stuck on its last stage forever. + * optional fork — emits [MoveStage.ERROR] and rolls back a worktree that was already created. + * The frontend collector has no error handling of its own, so a silent flow completion would + * leave the Agent Manager row stuck on its last stage forever. */ - override suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow = flow { + override suspend fun moveToWorktree(directory: String, sessionId: String?, branch: String): Flow = flow { val base = Path.of(directory).normalize() LOG.info("worktree move requested: dir=$base session=$sessionId branch=$branch") // Both survive the try so `finally` can drop temp patches and the failure paths can drop a @@ -241,11 +241,14 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi { emit(MoveProgressDto(MoveStage.ERROR, error = applied.error ?: "Failed to apply changes to worktree")) return@flow } - emit(MoveProgressDto(MoveStage.FORKING)) - val forked = withContext(Dispatchers.IO) { service().sessions.fork(sessionId, worktree.path) } + // A session-less move transfers changes only: nothing to fork, so no FORKING stage. + val forked = sessionId?.let { id -> + emit(MoveProgressDto(MoveStage.FORKING)) + withContext(Dispatchers.IO) { service().sessions.fork(id, worktree.path) } + } leftover = null - LOG.info("worktree move done: worktree=${worktree.path} session=${forked.id}") - emit(MoveProgressDto(MoveStage.DONE, worktree = worktree, session = forked.id)) + LOG.info("worktree move done: worktree=${worktree.path} session=${forked?.id}") + emit(MoveProgressDto(MoveStage.DONE, worktree = worktree, session = forked?.id)) } catch (e: CancellationException) { throw e } catch (e: Exception) { diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt index 7b51982febb3..28616656d018 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt @@ -549,6 +549,29 @@ class KiloWorktreeRpcApiImplTest { assertTrue(api.list(repo.toString()).worktrees.none { it.branch == "feature/x" }, "git must not track the worktree") } + @Test + fun `moveToWorktree without a session copies changes and skips forking`() = runBlocking { + initRepo() + Files.writeString(repo.resolve("README.md"), "hello edited\n") + Files.writeString(repo.resolve("untracked.txt"), "brand new\n") + + // No session to fork, so the flow must run to DONE instead of throwing in the fork stage. + val events = api.moveToWorktree(repo.toString(), null, "feature/x").toList() + + assertEquals( + listOf(MoveStage.CAPTURING, MoveStage.CREATING, MoveStage.TRANSFERRING, MoveStage.DONE), + events.map { it.stage }, + ) + val done = events.last() + assertNull(done.session, "a session-less move must not report a forked session") + val worktree = assertNotNull(done.worktree) + val target = Path.of(worktree.path) + assertEquals("hello edited\n", Files.readString(target.resolve("README.md"))) + assertEquals("brand new\n", Files.readString(target.resolve("untracked.txt"))) + // The transfer is a copy: the source keeps its work. + assertEquals("hello edited\n", Files.readString(repo.resolve("README.md"))) + } + private fun statusOf(dir: Path): String { val cmd = GeneralCommandLine(listOf("git", "status", "--porcelain")).withWorkDirectory(dir.toFile()) return CapturingProcessHandler(cmd).runProcess(30_000).stdout diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt index 761c0581b53a..a44a7b0d108c 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/KiloToolWindowFactory.kt @@ -140,12 +140,12 @@ internal class KiloToolWindowSetupService( toolWindow.contentManager.addContent(chatContent) toolWindow.contentManager.addContent(agentContent) val agents = { toolWindow.contentManager.setSelectedContent(agentContent, true) } - // The chat branch dock's "New Worktree" action switches to the Agent Manager tab and - // opens its New Worktree dialog, matching the VS Code sidebar dock. + // The chat branch dock's "New Worktree" action opens the Agent Manager's New Worktree + // dialog and only switches to that tab once the user confirms. The dialog is anchored on + // the chat panel because the Agents content may not be in a window hierarchy yet. manager.onNewWorktree = { Telemetry.send("New Worktree Clicked", mapOf("surface" to "chat_dock")) - agents() - agentManagerPanel.configure() + agentManagerPanel.configure(anchor = chat, onCreate = { agents() }) } manager.onMoveToWorktree = { id, dir -> agents() diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt index cc41f74f0154..e1b17be04409 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt @@ -11,7 +11,8 @@ import com.intellij.openapi.util.IconLoader /** * "Move to Worktree" action shown in the chat branch dock. Visible only when there is something to - * move (a conversation or local changes). + * move (a conversation or local changes). Without a session the wording drops the conversation: the + * move copies the local changes into the worktree and starts a fresh session there. */ class ChatMoveToWorktreeAction : AnAction(), DumbAware { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT @@ -26,17 +27,19 @@ class ChatMoveToWorktreeAction : AnAction(), DumbAware { e.presentation.isEnabledAndVisible = dock.moveEnabled() e.presentation.icon = BRANCH e.presentation.text = KiloBundle.message("session.dock.move") - e.presentation.description = moveTooltip(dock.changeCount()) + e.presentation.description = moveTooltip(dock.changeCount(), dock.hasSession()) } override fun actionPerformed(e: AnActionEvent) { e.getData(ChatDockKeys.DOCK)?.triggerMove() } - private fun moveTooltip(count: Int): String = when (count) { - 0 -> KiloBundle.message("session.dock.move.tooltip.empty") - 1 -> KiloBundle.message("session.dock.move.tooltip.one") - else -> KiloBundle.message("session.dock.move.tooltip.other", count) + private fun moveTooltip(count: Int, session: Boolean): String = when { + session && count == 0 -> KiloBundle.message("session.dock.move.tooltip.empty") + session && count == 1 -> KiloBundle.message("session.dock.move.tooltip.one") + session -> KiloBundle.message("session.dock.move.tooltip.other", count) + count == 1 -> KiloBundle.message("session.dock.move.tooltip.changes.one") + else -> KiloBundle.message("session.dock.move.tooltip.changes.other", count) } private companion object { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 68f8e77e0252..fd8410e51f26 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt @@ -2,6 +2,7 @@ package ai.kilocode.client.agentManager import ai.kilocode.client.KiloNotifications import ai.kilocode.client.agentManager.worktree.NewWorktreeDialog +import ai.kilocode.client.agentManager.worktree.NewWorktreeHandle import ai.kilocode.client.agentManager.worktree.GhBanner import ai.kilocode.client.agentManager.worktree.WorktreeController import ai.kilocode.client.agentManager.worktree.WorktreeDataKeys @@ -65,6 +66,7 @@ import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import java.awt.Color +import java.awt.Component import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener import javax.swing.JComponent @@ -77,6 +79,16 @@ class AgentManagerPanel( parent: Disposable, private val controller: WorktreeController, private val project: Project? = null, + private val dialog: (Component, Project) -> NewWorktreeHandle = { anchor, target -> + NewWorktreeDialog( + anchor, + target, + controller.directory, + controller.suggestName(), + controller.defaultBranch, + controller.branches, + ) + }, ) : BorderLayoutPanel(), Disposable, UiDataProvider { private val provider = WorktreeDeleteProvider() private val edit = RenameAction() @@ -155,23 +167,21 @@ class AgentManagerPanel( project?.service()?.refreshPr() } - /** Opens the New Worktree dialog. */ - fun configure() { + /** + * Opens the New Worktree dialog anchored at [anchor]. The worktree is created only after the + * dialog closes, so [onCreate] — e.g. the chat dock switching the tool window to this panel — + * never competes with the modal dialog for focus. + */ + fun configure(anchor: Component = this, onCreate: () -> Unit = {}) { val target = project ?: return - NewWorktreeDialog( - this, - target, - controller.directory, - controller.suggestName(), - controller.defaultBranch, - controller.branches, - onCreate = { branch, base, prompt -> - controller.create(branch, base, prompt = prompt) - }, - ).show() + val handle = dialog(anchor, target) + if (!handle.showAndGet()) return + val plan = handle.result() ?: return + onCreate() + controller.create(plan.branch, plan.base, prompt = plan.prompt) } - internal fun move(sessionId: String, directory: String) = controller.move(sessionId, directory) + internal fun move(sessionId: String?, directory: String) = controller.move(sessionId, directory) private fun remove(item: WorktreeDto, force: Boolean) { controller.remove(item, force, onFailure = { result -> notifyFailed(item, result, force) }) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt index 9a1f4fca5c4c..efa8230457c1 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt @@ -112,7 +112,7 @@ class KiloWorktreeService internal constructor( * Long-lived move flow. Routed through [durable] (via [call]) so it survives reconnects and * backend restarts while the move runs. */ - suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow = + suspend fun moveToWorktree(directory: String, sessionId: String?, branch: String): Flow = call { moveToWorktree(directory, sessionId, branch) } suspend fun create(directory: String, req: CreateWorktreeRequestDto): CreateWorktreeResultDto = diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/NewWorktreeDialog.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/NewWorktreeDialog.kt index efd3a047b77f..0f7366015c8e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/NewWorktreeDialog.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/NewWorktreeDialog.kt @@ -42,7 +42,19 @@ import javax.swing.JTextField import javax.swing.event.DocumentEvent import javax.swing.plaf.basic.BasicComboPopup -private const val NAME_COLUMNS = 100 +private const val NAME_COLUMNS = 67 + +/** What the user confirmed in the New Worktree dialog. */ +data class NewWorktreePlan(val branch: String, val base: String?, val prompt: PendingPrompt?) + +/** + * The New Worktree dialog as seen by its caller: show it, then read what the user confirmed. + * [result] stays null while the dialog is cancelled or its input never validates. + */ +interface NewWorktreeHandle { + fun showAndGet(): Boolean + fun result(): NewWorktreePlan? +} /** * New Worktree dialog with parity to the VS Code Agent Manager dialog: a worktree name (top), an @@ -50,8 +62,9 @@ private const val NAME_COLUMNS = 100 * branch name + base branch (bottom). Creating a worktree starts a session automatically with the * prompt. * - * The dialog performs no worktree work itself — it invokes [onCreate] and closes; the panel drives - * the controller. Mode, model, and reasoning selections are persisted the same way the chat prompt + * The dialog performs no worktree work itself — it records the confirmed [result] and closes; the + * panel then drives the controller, so no view switch or worktree work runs while the modal dialog + * still owns focus. Mode, model, and reasoning selections are persisted the same way the chat prompt * does, so the freshly-started session inherits them. */ internal class NewWorktreeDialog( @@ -61,14 +74,13 @@ internal class NewWorktreeDialog( private val suggestedName: String, private val defaultBase: String, private val branches: List, - private val onCreate: (branch: String, base: String?, prompt: PendingPrompt?) -> Unit, private val app: KiloAppService = service(), private val workspaces: KiloWorkspaceService = service(), -) : DialogWrapper(parent, false) { +) : DialogWrapper(parent, false), NewWorktreeHandle { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - // A wide name field so the dialog opens wide enough to type long worktree names and prompts. + // Sizes the dialog: the name field is its widest fixed-width child. private val name = JBTextField(NAME_COLUMNS).apply { emptyText.text = KiloBundle.message("worktree.dialog.name.placeholder") } @@ -99,6 +111,8 @@ internal class NewWorktreeDialog( } private var syncing = false + private var plan: NewWorktreePlan? = null + /** The agent (mode) for the new session; model selections persist against it. */ private var agent: String? = null @@ -125,9 +139,12 @@ internal class NewWorktreeDialog( /** The built content, so tests can drive the real Swing tree before the dialog is shown. */ internal fun centerComponent(): JComponent = center ?: error("center panel not built") + override fun result(): NewWorktreePlan? = plan + override fun getPreferredFocusedComponent(): JComponent = prompt.defaultFocusedComponent - override fun getDimensionServiceKey(): String = "ai.kilocode.NewWorktreeDialog" + // Versioned: DialogWrapper persists the size per key, so a stale entry would keep the old width. + override fun getDimensionServiceKey(): String = "ai.kilocode.NewWorktreeDialog.v2" override fun doOKAction() = submitCreate() @@ -301,7 +318,7 @@ internal class NewWorktreeDialog( val resolved = explicit.ifEmpty { name.text.trim() }.ifEmpty { suggestedName } val target = resolvedBase() if (!validBase(target)) return - onCreate(resolved, target, pending(text)) + plan = NewWorktreePlan(resolved, target, pending(text)) close(OK_EXIT_CODE) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt index f96a7fb7c414..2a7e8ff20a1e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt @@ -213,9 +213,14 @@ class WorktreeController( } } + /** + * Copies working-tree changes into a new worktree. When [sessionId] is set, the source session is + * also forked into the worktree; otherwise the opened worktree starts with a fresh session. + */ @RequiresEdt - fun move(sessionId: String, source: String = directory) { - if (!moves.add(sessionId)) return + fun move(sessionId: String?, source: String = directory) { + val key = sessionId ?: source + if (!moves.add(key)) return val branch = suggestName() val temp = WorktreeDto("pending:$branch:${System.nanoTime()}", branch, branch, "pending:$branch") pending[temp.id] = temp @@ -225,7 +230,7 @@ class WorktreeController( cs.launch { var stage = MoveStage.CAPTURING runCatching { - abort(sessionId, source) + if (sessionId != null) abort(sessionId, source) service.moveToWorktree(source, sessionId, branch).collect { event -> edt { if (event.stage != MoveStage.ERROR) stage = event.stage @@ -233,7 +238,7 @@ class WorktreeController( refresh(temp) when (event.stage) { MoveStage.DONE -> { - moves.remove(sessionId) + moves.remove(key) pending.remove(temp.id) tasks.remove(temp.id) val worktree = event.worktree ?: return@edt @@ -244,14 +249,17 @@ class WorktreeController( // open; the tab's identity stays the worktree path alone. event.session?.let { service().put(worktree.path, it) } onSelect?.invoke(worktree.id) - telemetry("Continue in Worktree", mapOf("surface" to "sidebar")) + telemetry( + "Continue in Worktree", + mapOf("surface" to "sidebar", "session" to (sessionId != null).toString()), + ) } - MoveStage.ERROR -> failMove(sessionId, temp, event.error, stage) + MoveStage.ERROR -> failMove(key, temp, event.error, stage) else -> Unit } } } - }.onFailure { err -> edt { failMove(sessionId, temp, err.message, stage) } } + }.onFailure { err -> edt { failMove(key, temp, err.message, stage) } } } } @@ -331,8 +339,8 @@ class WorktreeController( return (0 until model.size).firstOrNull { model.getElementAt(it).id == id } ?: -1 } - private fun failMove(session: String, temp: WorktreeDto, err: String?, stage: MoveStage) { - moves.remove(session) + private fun failMove(key: String, temp: WorktreeDto, err: String?, stage: MoveStage) { + moves.remove(key) pending.remove(temp.id) tasks.remove(temp.id) model.remove(temp) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt index f64c359163e7..619ee030d3d3 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt @@ -25,7 +25,7 @@ interface SessionManager { val supportsMoveToWorktree: Boolean get() = false /** Opens the Move to Worktree flow. No-op unless [supportsMoveToWorktree] is true. */ - fun moveToWorktree(sessionId: String, directory: String) {} + fun moveToWorktree(sessionId: String?, directory: String) {} fun showHistory(back: (() -> Unit)? = null) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt index df20db529669..440b3579ea5f 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionSidePanelManager.kt @@ -53,7 +53,7 @@ class SessionSidePanelManager( var onNewWorktree: (() -> Unit)? = null /** Wired by the tool window to move the current chat into an Agent Manager worktree row. */ - var onMoveToWorktree: ((String, String) -> Unit)? = null + var onMoveToWorktree: ((String?, String) -> Unit)? = null override val supportsNewWorktree: Boolean get() = onNewWorktree != null @@ -63,7 +63,7 @@ class SessionSidePanelManager( onNewWorktree?.invoke() } - override fun moveToWorktree(sessionId: String, directory: String) { + override fun moveToWorktree(sessionId: String?, directory: String) { onMoveToWorktree?.invoke(sessionId, directory) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt index 5ad144c4ed3d..83789ad5a656 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionUi.kt @@ -993,8 +993,7 @@ class SessionUi( /** Starts the Move to Worktree flow for the current session through the side-panel manager. */ @RequiresEdt private fun moveToWorktree() { - val id = controller.id ?: return - manager?.moveToWorktree(id, controller.sessionDirectory) + manager?.moveToWorktree(controller.id, controller.sessionDirectory) } @RequiresEdt diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt index eba539a00b7b..3f11676e3dcd 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt @@ -33,8 +33,8 @@ import java.awt.Dimension * * The two actions are registered platform actions (`Kilo.Chat.NewWorktree`, `Kilo.Chat.MoveToWorktree`) * rendered through an [com.intellij.openapi.actionSystem.ActionToolbar]; each is invisible when it is - * not enabled, so the dock never shows a lone action. The dock exposes its state to those actions via - * [ChatDockKeys.DOCK]. Collapses to nothing unless it has a PR, changes, or an enabled action. + * not enabled. The dock exposes its state to those actions via [ChatDockKeys.DOCK]. Collapses to + * nothing unless it has a PR, changes, messages, or an enabled action. * * The action row is offered only while the session is idle: an active turn ([setBusy]) withdraws it. * The PR row stays through a turn — it is informational, not an action. @@ -112,25 +112,26 @@ internal class BranchDock( } /** - * Whether the chat already has a persisted session. A brand-new session has no id until its - * first prompt, and there is nothing to move until then — even in a repository with local - * changes, which would otherwise activate the dock. + * Whether the chat already has a persisted session. A session-less move transfers only local + * changes; this value affects action wording, not visibility. */ @RequiresEdt fun setHasSession(value: Boolean) { if (hasSession == value) return hasSession = value - sync() + syncToolbar() } // ---- state read by the toolbar actions ---- fun newWorktreeEnabled(): Boolean = onNewWorktree != null && dockActive() - fun moveEnabled(): Boolean = onMove != null && hasSession && dockActive() + fun moveEnabled(): Boolean = onMove != null && dockActive() fun changeCount(): Int = files.size + fun hasSession(): Boolean = hasSession + fun triggerNewWorktree() = onNewWorktree?.invoke() ?: Unit fun triggerMove() = onMove?.invoke() ?: Unit diff --git a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties index 0d41529c9e8c..aeff0f994ae1 100644 --- a/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties +++ b/packages/kilo-jetbrains/frontend/src/main/resources/messages/KiloBundle.properties @@ -145,6 +145,8 @@ session.dock.move=Move to Worktree session.dock.move.tooltip.empty=Move this conversation and your current local changes into a dedicated worktree for isolated follow-up work. session.dock.move.tooltip.one=Move this conversation and 1 changed file into a dedicated worktree for isolated follow-up work. session.dock.move.tooltip.other=Move this conversation and {0} changed files into a dedicated worktree for isolated follow-up work. +session.dock.move.tooltip.changes.one=Copy your 1 changed file into a dedicated worktree and continue there. +session.dock.move.tooltip.changes.other=Copy your {0} changed files into a dedicated worktree and continue there. diff.editor.session.title=Session Changes diff.editor.inline.title.named={0} ({1}) diff.editor.changedFiles.title=Changed files diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt index eef6909b3bde..f436a11ab0d4 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/AgentManagerPanelTest.kt @@ -3,6 +3,10 @@ package ai.kilocode.client.agentManager import ai.kilocode.client.util.edtWait import ai.kilocode.client.agentManager.worktree.KiloWorktreeService import ai.kilocode.client.agentManager.worktree.GhStatusCoordinator +import ai.kilocode.client.agentManager.worktree.NewWorktreeHandle +import ai.kilocode.client.agentManager.worktree.NewWorktreePlan +import ai.kilocode.client.agentManager.worktree.PendingPrompt +import ai.kilocode.client.agentManager.worktree.PendingWorktreePrompt import ai.kilocode.client.agentManager.worktree.WorktreeController import ai.kilocode.client.agentManager.worktree.WorktreeEditorMatcher import ai.kilocode.client.agentManager.worktree.WorktreeEditorMatchers @@ -122,6 +126,40 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(false, file.getUserData(KiloVfsManager.FOCUS)) } + fun `test configure creates the worktree only after the dialog closes`() { + val order = mutableListOf() + val plan = NewWorktreePlan("feature/y", "main", PendingPrompt("build it")) + val controller = WorktreeController(service, "/test", coroutines.scope) + val panel = edt { + AgentManagerPanel(testRootDisposable, controller, project, dialog = { _, _ -> FakeWorktreeDialog(plan, order) }) + } + + edt { panel.configure(onCreate = { order += "switch" }) } + flush() + + // The view switch happens after the modal dialog is gone and before the worktree row lands. + assertEquals(listOf("show", "switch"), order) + val created = edt { controller.model.getElementAt(0) } + assertEquals("feature/y", created.branch) + assertEquals("main", rpc.creates.single().baseBranch) + edt { assertEquals("build it", service().take(created.path)?.text) } + } + + fun `test configure does nothing when the dialog is cancelled`() { + val order = mutableListOf() + val controller = WorktreeController(service, "/test", coroutines.scope) + val panel = edt { + AgentManagerPanel(testRootDisposable, controller, project, dialog = { _, _ -> FakeWorktreeDialog(null, order) }) + } + + edt { panel.configure(onCreate = { order += "switch" }) } + flush() + + assertEquals(listOf("show"), order) + assertEquals(0, edt { controller.model.size }) + assertTrue(rpc.creates.isEmpty()) + } + fun `test panel hides worktree search field`() { val controller = WorktreeController(service, "/test", coroutines.scope) val panel = edt { AgentManagerPanel(testRootDisposable, controller) } @@ -816,3 +854,16 @@ class AgentManagerPanelTest : BasePlatformTestCase() { private fun pump() = pumpEdt() } + +/** Stands in for the modal New Worktree dialog: records that it was shown, then reports [plan]. */ +private class FakeWorktreeDialog( + private val plan: NewWorktreePlan?, + private val order: MutableList, +) : NewWorktreeHandle { + override fun showAndGet(): Boolean { + order += "show" + return plan != null + } + + override fun result(): NewWorktreePlan? = plan +} diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt index a6060386b6b0..9e1aca1bc630 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeControllerTest.kt @@ -358,7 +358,53 @@ class WorktreeControllerTest : BasePlatformTestCase() { assertNull(service().take(done.path)) } assertEquals(done.id, selected.last()) - assertTrue(events.any { it.first == "Continue in Worktree" && it.second["surface"] == "sidebar" }) + assertTrue( + events.any { + it.first == "Continue in Worktree" && it.second["surface"] == "sidebar" && it.second["session"] == "true" + }, + ) + } + + fun `test move without a session transfers changes and skips forking`() { + val done = WorktreeDto("/wt/moved", "moved", "moved", "/wt/moved") + rpc.moveScript = listOf( + MoveProgressDto(MoveStage.CREATING), + MoveProgressDto(MoveStage.TRANSFERRING), + MoveProgressDto(MoveStage.DONE, worktree = done), + ) + val selected = mutableListOf() + val aborts = mutableListOf>() + val events = mutableListOf>>() + val controller = controller(abort = { id, dir -> aborts += id to dir }, telemetry = { name, props -> events += name to props }) + controller.onSelect = { selected += it } + + ApplicationManager.getApplication().invokeAndWait { controller.move(null, "/repo") } + flush() + + assertTrue("a session-less move has no turn to abort", aborts.isEmpty()) + assertEquals("/repo", rpc.moves.single().first) + assertNull(rpc.moves.single().second) + assertEquals(done, controller.model.getElementAt(0)) + // Nothing is queued for the worktree editor, so opening it starts a fresh session. + ApplicationManager.getApplication().invokeAndWait { + assertNull(service().take(done.path)) + } + assertEquals(done.id, selected.last()) + assertTrue(events.any { it.first == "Continue in Worktree" && it.second["session"] == "false" }) + } + + fun `test duplicate move without a session is ignored while in flight`() { + rpc.moveScript = listOf(MoveProgressDto(MoveStage.DONE, worktree = WorktreeDto("/wt/moved", "moved", "moved", "/wt/moved"))) + val controller = controller() + + ApplicationManager.getApplication().invokeAndWait { + controller.move(null, "/repo") + controller.move(null, "/repo") + } + flush() + + assertEquals(1, controller.model.size) + assertEquals(1, rpc.moves.size) } fun `test move failure removes placeholder and reports last stage`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/NewWorktreeDialogTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/NewWorktreeDialogTest.kt index 0aa0fadf2a84..2896016d1081 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/NewWorktreeDialogTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/NewWorktreeDialogTest.kt @@ -39,7 +39,6 @@ class NewWorktreeDialogTest : BasePlatformTestCase() { private lateinit var workspaces: KiloWorkspaceService private lateinit var sessionRpc: FakeSessionRpcApi private var dialog: NewWorktreeDialog? = null - private val created = mutableListOf>() override fun setUp() { super.setUp() @@ -82,10 +81,8 @@ class NewWorktreeDialogTest : BasePlatformTestCase() { } flushUntil { edt { prompt().isSendEnabled } } edt { prompt().send() } - flushUntil { created.isNotEmpty() } - dialog = null - assertEquals("plan", created.single().third?.agent) + assertEquals("plan", submitted().prompt?.agent) // Picking a mode must no longer mutate the global default_agent config. assertTrue(sessionRpc.configs.none { it.second.agent != null }) } @@ -116,13 +113,11 @@ class NewWorktreeDialogTest : BasePlatformTestCase() { } flushUntil { edt { prompt().isSendEnabled } } edt { prompt().send() } - flushUntil { created.isNotEmpty() } - dialog = null - val entry = created.single() - assertEquals("agent/foo", entry.first) - assertEquals("main", entry.second) - val payload = requireNotNull(entry.third) + val entry = submitted() + assertEquals("agent/foo", entry.branch) + assertEquals("main", entry.base) + val payload = requireNotNull(entry.prompt) assertEquals("build the thing", payload.text) assertEquals("build", payload.agent) assertEquals("kilo", payload.provider) @@ -158,10 +153,8 @@ class NewWorktreeDialogTest : BasePlatformTestCase() { } flushUntil { edt { prompt().isSendEnabled } } edt { prompt().send() } - flushUntil { created.isNotEmpty() } - dialog = null - assertEquals("main", created.single().second) + assertEquals("main", submitted().base) } fun `test creating with fuzzy base branch uses matching branch`() { @@ -173,10 +166,8 @@ class NewWorktreeDialogTest : BasePlatformTestCase() { } flushUntil { edt { prompt().isSendEnabled } } edt { prompt().send() } - flushUntil { created.isNotEmpty() } - dialog = null - assertEquals("release/candidate", created.single().second) + assertEquals("release/candidate", submitted().base) } fun `test creating with unknown base branch does not create`() { @@ -190,7 +181,7 @@ class NewWorktreeDialogTest : BasePlatformTestCase() { edt { prompt().send() } flush() - assertTrue(created.isEmpty()) + assertNull(plan()) } private fun open(branches: List = listOf("main")) { @@ -202,13 +193,20 @@ class NewWorktreeDialogTest : BasePlatformTestCase() { "agent/foo", "main", branches, - onCreate = { branch, base, prompt -> created.add(Triple(branch, base, prompt)) }, app, workspaces, ) } } + private fun plan(): NewWorktreePlan? = edt { requireNotNull(dialog).result() } + + /** Waits for the dialog to accept a create, then forgets it: closing already disposed it. */ + private fun submitted(): NewWorktreePlan { + flushUntil { plan() != null } + return requireNotNull(plan()).also { dialog = null } + } + private fun workspace(): ModelsWorkspaceDto { val providers = ProvidersDto( providers = listOf( diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt index 7cd31a1406e2..4429858362ea 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/SessionUiLayoutTest.kt @@ -191,13 +191,13 @@ class SessionUiLayoutTest : SessionUiTestBase() { } fun `test dock move delegates to manager without progress state`() { - val calls = mutableListOf>() + val calls = mutableListOf>() val owner = object : SessionManager { override fun newSession() {} override fun showHistory(back: (() -> Unit)?) {} override fun openSession(ref: SessionRef) {} override val supportsMoveToWorktree: Boolean get() = true - override fun moveToWorktree(sessionId: String, directory: String) { + override fun moveToWorktree(sessionId: String?, directory: String) { calls += sessionId to directory } } @@ -219,12 +219,16 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertTrue(dock.moveEnabled()) } - fun `test dock move stays disabled for a new session with local changes`() { + fun `test dock move forwards a null session for a new session with local changes`() { + val calls = mutableListOf>() val owner = object : SessionManager { override fun newSession() {} override fun showHistory(back: (() -> Unit)?) {} override fun openSession(ref: SessionRef) {} override val supportsMoveToWorktree: Boolean get() = true + override fun moveToWorktree(sessionId: String?, directory: String) { + calls += sessionId to directory + } } val worktree = FakeWorktreeRpcApi().apply { branchResult = BranchStatusDto(branch = "main", availability = GhAvailability.OK) @@ -232,18 +236,18 @@ class SessionUiLayoutTest : SessionUiTestBase() { ApplicationManager.getApplication() .replaceService(KiloWorktreeService::class.java, KiloWorktreeService(scope, worktree), testRootDisposable) workspaceRpc.branchDiffs.add(DiffFileDto("src/A.kt", 2, 1)) - // A brand-new sidebar session: no id until the first prompt, so nothing exists to move even - // though the local changes keep the dock on screen. + // A brand-new sidebar session has no id until its first prompt, but the local changes alone + // are worth moving: the worktree gets the changes and starts its own session. ui = newUi(manager = owner) settle() val dock = find(ui) assertTrue(dock.isVisible) - assertFalse(dock.moveEnabled()) + assertTrue(dock.moveEnabled()) - showMessages() + dock.triggerMove() - assertTrue(dock.moveEnabled()) + assertEquals(listOf>(null to "/test"), calls) } fun `test a failed branch status leaves the dock inactive instead of assuming healthy git`() { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt index 15e05df843a3..18435743d069 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt @@ -148,6 +148,7 @@ class BranchDockTest : BasePlatformTestCase() { assertTrue(p.isVisible) assertTrue(p.isEnabled) assertEquals(KiloBundle.message("session.dock.move"), p.text) + assertEquals(KiloBundle.message("session.dock.move.tooltip.empty"), p.description) } fun `test move action visible with changes and no messages`() { @@ -157,22 +158,23 @@ class BranchDockTest : BasePlatformTestCase() { dock.setChanges(listOf(DiffFileDto("src/A.kt", 2, 1))) dock.setHasSession(true) } - assertTrue(update(ChatMoveToWorktreeAction(), dock).isVisible) + val p = update(ChatMoveToWorktreeAction(), dock) + assertTrue(p.isVisible) + assertEquals(KiloBundle.message("session.dock.move.tooltip.one"), p.description) } - fun `test move action hidden until the chat has a session`() { + fun `test move action visible with changes and no session`() { val dock = dock() edt { dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) - dock.setChanges(listOf(DiffFileDto("src/A.kt", 2, 1))) + dock.setChanges(listOf(DiffFileDto("src/A.kt", 2, 1), DiffFileDto("src/B.kt", 1, 0))) } - // A new sidebar session has no id until its first prompt, so there is nothing to move even - // though the local changes activate the dock. - assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) - - edt { dock.setHasSession(true) } - - assertTrue(update(ChatMoveToWorktreeAction(), dock).isVisible) + // A new sidebar session has no id until its first prompt; the local changes alone are worth + // moving, so the action is offered with changes-only wording. + val p = update(ChatMoveToWorktreeAction(), dock) + assertTrue(p.isVisible) + assertTrue(p.isEnabled) + assertEquals(KiloBundle.message("session.dock.move.tooltip.changes.other", 2), p.description) } fun `test move action hidden with nothing to move`() { @@ -194,7 +196,7 @@ class BranchDockTest : BasePlatformTestCase() { fun `test move action invokes callback`() { var moved = 0 - val dock = edt { BranchDock(openDiff = {}, onMove = { moved++ }).also { it.setHasSession(true) } } + val dock = edt { BranchDock(openDiff = {}, onMove = { moved++ }) } val action = ChatMoveToWorktreeAction() val event = event(action, dock) edt { ActionUtil.updateAction(action, event) } @@ -207,7 +209,6 @@ class BranchDockTest : BasePlatformTestCase() { edt { dock.setBranch(BranchStatusDto(branch = "feature-x", worktree = false, availability = GhAvailability.OK)) dock.setHasMessages(true) - dock.setHasSession(true) } assertFalse(update(ChatMoveToWorktreeAction(), dock).isVisible) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt index b9e85c2c8501..31a3fbf98098 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeWorktreeRpcApi.kt @@ -31,7 +31,7 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { /** When set, [branchStatus] throws it instead of answering. */ var branchThrows: Exception? = null var currentBranch: String? = null - val moves = CopyOnWriteArrayList>() + val moves = CopyOnWriteArrayList>() /** Progress events emitted by [moveToWorktree], in order. */ var moveScript: List = emptyList() val creates = CopyOnWriteArrayList() @@ -101,7 +101,7 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { return branchResult } - override suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow { + override suspend fun moveToWorktree(directory: String, sessionId: String?, branch: String): Flow { assertNotEdt("moveToWorktree") moves.add(Triple(directory, sessionId, branch)) return moveScript.asFlow() diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt index 0db24c99d448..3fe5072cf198 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt @@ -53,10 +53,11 @@ interface KiloWorktreeRpcApi : RemoteApi { /** * Moves the session [sessionId] running in [directory] into a fresh worktree on [branch]: * captures uncommitted changes, creates the worktree at the source HEAD, transfers the changes, - * then forks the session into it. Emits one [MoveProgressDto] per stage; [branch] is generated - * on the frontend from the known branch list. + * then forks the session into it. When [sessionId] is null, only the working-tree changes are + * transferred and no FORKING stage is emitted. [branch] is generated on the frontend from the + * known branch list. */ - suspend fun moveToWorktree(directory: String, sessionId: String, branch: String): Flow + suspend fun moveToWorktree(directory: String, sessionId: String?, branch: String): Flow suspend fun listBranches(directory: String): WorktreeBranchesDto suspend fun create(directory: String, request: CreateWorktreeRequestDto): CreateWorktreeResultDto From edf60412f92e7a45e651fc2b1a4fd9f78a190a0e Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 12:52:35 -0400 Subject: [PATCH 25/30] fix(jetbrains): align chat dock row spacing --- .../ai/kilocode/client/session/ui/header/BranchDock.kt | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt index 3f11676e3dcd..6ca74cf33f9a 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt @@ -77,7 +77,7 @@ internal class BranchDock( super.updateUI() border = JBUI.Borders.compound( JBUI.Borders.customLineTop(JBUI.CurrentTheme.EditorTabs.borderColor()), - JBUI.Borders.empty(UiStyle.Gap.xs(), UiStyle.Gap.sm()), + JBUI.Borders.empty(UiStyle.Gap.md(), UiStyle.Gap.sm(), UiStyle.Gap.md(), UiStyle.Gap.sm()), ) } @@ -172,12 +172,6 @@ internal class BranchDock( ActivityTracker.getInstance().inc() } - override fun getPreferredSize(): Dimension { - val base = super.getPreferredSize() - // Reserve a stable row height so the transcript does not jump as stats/PR arrive late. - return Dimension(base.width, maxOf(base.height, JBUI.scale(ROW_HEIGHT))) - } - override fun getMinimumSize(): Dimension = preferredSize override fun getMaximumSize(): Dimension = Dimension(Int.MAX_VALUE, preferredSize.height) @@ -188,7 +182,6 @@ internal class BranchDock( } private companion object { - const val ROW_HEIGHT = 34 const val PLACE = "KiloChatBranchDock" } } From 2860d1a4689c209c7735a6d0a7e8ebf717a4ca51 Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 13:04:58 -0400 Subject: [PATCH 26/30] fix(jetbrains): tighten chat dock row height --- .../ai/kilocode/client/session/ui/header/BranchDock.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt index 6ca74cf33f9a..bdc2e6a88f96 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt @@ -77,7 +77,7 @@ internal class BranchDock( super.updateUI() border = JBUI.Borders.compound( JBUI.Borders.customLineTop(JBUI.CurrentTheme.EditorTabs.borderColor()), - JBUI.Borders.empty(UiStyle.Gap.md(), UiStyle.Gap.sm(), UiStyle.Gap.md(), UiStyle.Gap.sm()), + JBUI.Borders.empty(0, 0), ) } @@ -172,6 +172,12 @@ internal class BranchDock( ActivityTracker.getInstance().inc() } + override fun getPreferredSize(): Dimension { + val base = super.getPreferredSize() + // Reserve a stable row height so the transcript does not jump as stats/PR arrive late. + return Dimension(base.width, maxOf(base.height, JBUI.scale(ROW_HEIGHT))) + } + override fun getMinimumSize(): Dimension = preferredSize override fun getMaximumSize(): Dimension = Dimension(Int.MAX_VALUE, preferredSize.height) @@ -182,6 +188,7 @@ internal class BranchDock( } private companion object { + const val ROW_HEIGHT = 34 const val PLACE = "KiloChatBranchDock" } } From d4f869d971a20e1a254e7994de4d40093609b10f Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 14:33:50 -0400 Subject: [PATCH 27/30] fix(jetbrains): scope worktree session history --- .../jetbrains-worktree-session-history.md | 5 + .../backend/app/KiloBackendSessionManager.kt | 42 ++++++++ .../kilocode/backend/cli/KiloCliDataParser.kt | 25 +++++ .../backend/rpc/KiloSessionRpcApiImpl.kt | 4 + .../app/KiloBackendActivityManagerTest.kt | 9 +- .../app/KiloBackendSessionManagerTest.kt | 95 +++++++++++++++++++ .../backend/cli/KiloCliDataParserTest.kt | 86 +++++++++++++++++ .../worktree/WorktreeSessionListController.kt | 28 ++++++ .../kilocode/client/app/KiloSessionService.kt | 10 +- .../session/controller/SessionController.kt | 13 +++ .../WorktreeSessionListControllerTest.kt | 63 ++++++++++++ .../controller/SessionControllerTestBase.kt | 16 ++++ .../session/controller/ViewSwitchingTest.kt | 51 ++++++++++ .../client/testing/FakeSessionRpcApi.kt | 9 ++ .../ai/kilocode/rpc/KiloSessionRpcApi.kt | 9 +- .../kotlin/ai/kilocode/rpc/dto/SessionDto.kt | 21 ++++ 16 files changed, 483 insertions(+), 3 deletions(-) create mode 100644 .changeset/jetbrains-worktree-session-history.md diff --git a/.changeset/jetbrains-worktree-session-history.md b/.changeset/jetbrains-worktree-session-history.md new file mode 100644 index 000000000000..6f33e960c90f --- /dev/null +++ b/.changeset/jetbrains-worktree-session-history.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Scope chat session history to the worktree you have open, so a worktree no longer lists sessions from the main checkout or sibling worktrees, and show sessions started in another project frame in Agent Manager as they happen. diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt index b9b8b2eea04b..bd76ef926348 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt @@ -7,6 +7,8 @@ import ai.kilocode.jetbrains.api.client.DefaultApi import ai.kilocode.jetbrains.api.model.GlobalSession import ai.kilocode.jetbrains.api.model.SessionStatus import ai.kilocode.rpc.dto.CloudSessionListDto +import ai.kilocode.rpc.dto.SessionChangeDto +import ai.kilocode.rpc.dto.SessionChangeKindDto import ai.kilocode.rpc.dto.SessionDto import ai.kilocode.rpc.dto.SessionListDto import ai.kilocode.rpc.dto.SessionRevertDto @@ -15,9 +17,11 @@ import ai.kilocode.rpc.dto.SessionSummaryDto import ai.kilocode.rpc.dto.SessionTimeDto import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @@ -56,6 +60,10 @@ class KiloBackendSessionManager( private val _statuses = MutableStateFlow>(emptyMap()) val statuses: StateFlow> = _statuses.asStateFlow() + // Field, not created in start(), so frontend subscribers survive a disconnect/reconnect. + private val _changes = MutableSharedFlow(extraBufferCapacity = 64) + val changes: SharedFlow = _changes.asSharedFlow() + private var client: DefaultApi? = null private var http: OkHttpClient? = null private var base: String? = null @@ -83,6 +91,7 @@ class KiloBackendSessionManager( } } } + KiloCliDataParser.parseSessionChange(event.type, event.data)?.let { track(it) } } } log.info("Session manager started") @@ -106,6 +115,31 @@ class KiloBackendSessionManager( private fun requireClient(): DefaultApi = client ?: throw IllegalStateException("Session manager not started") + /** + * Records a session lifecycle change and republishes it. + * + * Keeping [owned] current from events — not just from listings — is what lets + * [KiloBackendActivityManager] resolve a directory for a session this frame never listed, so + * Agent Manager can badge a worktree whose session was started in another project frame. + * + * Publishing is non-blocking: this runs on the collector that also feeds [statuses], and a slow + * change subscriber must never stall status handling. A dropped change only costs a list + * refresh, which the next change or a reopened tab recovers. + */ + private fun track(change: SessionChangeDto) { + if (change.kind == SessionChangeKindDto.DELETED) { + owned.remove(change.id) + directories.remove(change.id) + } else { + owned[change.id] = change.directory + } + val kind = change.kind.name.lowercase() + log.debug { "${ChatLogSummary.sid(change.id)} evt=session.$kind ${ChatLogSummary.dir(change.directory)}" } + if (!_changes.tryEmit(change)) { + log.warn("${ChatLogSummary.sid(change.id)} kind=session-change evt=session.$kind dropped=true") + } + } + // ------ session CRUD ------ fun list(dir: String): SessionListDto { @@ -117,11 +151,19 @@ class KiloBackendSessionManager( return SessionListDto(mapped, relevant) } + /** + * Recent root sessions for the worktree containing [dir]. + * + * `worktrees=true` resolves the git worktree family (and applies `archived=false`, which plain + * `GET /session` does not); `current=true` then narrows that family to the one worktree [dir] + * lives in, so a chat opened on a worktree never lists the main checkout's sessions. + */ fun recent(dir: String, limit: Int): SessionListDto { seed(dir) val raw = requireClient().experimentalSessionList( directory = dir, worktrees = true, + current = DefaultApi.CurrentExperimentalSessionList.TRUE, roots = JsonPrimitive(true), limit = limit.toDouble(), archived = JsonPrimitive(false), diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt index fec8354f8aec..a7f1afaefc9a 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/cli/KiloCliDataParser.kt @@ -68,6 +68,8 @@ import ai.kilocode.rpc.dto.QuestionInfoDto import ai.kilocode.rpc.dto.QuestionOptionDto import ai.kilocode.rpc.dto.QuestionReplyDto import ai.kilocode.rpc.dto.QuestionRequestDto +import ai.kilocode.rpc.dto.SessionChangeDto +import ai.kilocode.rpc.dto.SessionChangeKindDto import ai.kilocode.rpc.dto.SessionDto import ai.kilocode.rpc.dto.SessionRevertDto import ai.kilocode.rpc.dto.SessionStatusDto @@ -375,6 +377,29 @@ object KiloCliDataParser { return id to parseStatus(st) } + /** + * Parse an SSE `session.created` / `session.updated` / `session.deleted` event into a + * [SessionChangeDto]. All three carry the full session `info`, which is where the directory + * comes from. Returns null for any other type, or when there is no id or directory to act on. + */ + fun parseSessionChange(type: String, data: String): SessionChangeDto? { + val kind = when (type) { + "session.created" -> SessionChangeKindDto.CREATED + "session.updated" -> SessionChangeKindDto.UPDATED + "session.deleted" -> SessionChangeKindDto.DELETED + else -> return null + } + val obj = tryParseObject(data) ?: return null + val payload = obj["payload"]?.jsonObject ?: obj + val props = payload["properties"]?.jsonObject ?: obj + val info = props["info"]?.jsonObject + val id = props.str("sessionID")?.takeIf { it.isNotBlank() } + ?: info?.str("id")?.takeIf { it.isNotBlank() } + ?: return null + val dir = info?.str("directory")?.takeIf { it.isNotBlank() } ?: return null + return SessionChangeDto(id, dir, kind) + } + // ================================================================ // HTTP response parsing // ================================================================ diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloSessionRpcApiImpl.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloSessionRpcApiImpl.kt index 8b83922d8234..e4a0ec43b3b2 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloSessionRpcApiImpl.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloSessionRpcApiImpl.kt @@ -24,6 +24,7 @@ import ai.kilocode.rpc.dto.QuestionReplyDto import ai.kilocode.rpc.dto.QuestionRequestDto import ai.kilocode.rpc.dto.SessionDto import ai.kilocode.rpc.dto.SessionActivityDto +import ai.kilocode.rpc.dto.SessionChangeDto import ai.kilocode.rpc.dto.SessionListDto import ai.kilocode.rpc.dto.SessionStatusDto import com.intellij.openapi.components.service @@ -124,6 +125,9 @@ class KiloSessionRpcApiImpl internal constructor( override suspend fun activity(): Flow> = activity.activity + override suspend fun changes(): Flow = + sessions.changes + override suspend fun setDirectory(id: String, directory: String) = sessions.setDirectory(id, directory) diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt index ba13390a1cda..1a6d1f9f4ef6 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt @@ -34,7 +34,14 @@ class KiloBackendActivityManagerTest { scope.cancel() } - private fun start() = manager.start(statuses, { directories[it] }, events) + /** + * Starts the manager and waits until its event collector has subscribed. [events] has no + * replay, so an emit before that point is silently discarded and the test hangs. + */ + private suspend fun start() { + manager.start(statuses, { directories[it] }, events) + withTimeout(5_000) { events.subscriptionCount.first { it > 0 } } + } @Test fun `busy status with known directory emits running activity`() = runBlocking { diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendSessionManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendSessionManagerTest.kt index c5fc5433acb0..77aac0bd57c1 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendSessionManagerTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendSessionManagerTest.kt @@ -6,12 +6,17 @@ import ai.kilocode.backend.app.KiloBackendSessionManager import ai.kilocode.backend.testing.FakeCliServer import ai.kilocode.backend.testing.MockCliServer import ai.kilocode.backend.testing.TestLog +import ai.kilocode.rpc.dto.SessionChangeDto +import ai.kilocode.rpc.dto.SessionChangeKindDto +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout @@ -22,6 +27,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue class KiloBackendSessionManagerTest { @@ -50,6 +56,27 @@ class KiloBackendSessionManagerTest { } } + /** + * Runs [push] once a collector is attached to the change stream and returns the first change. + * The stream has no replay, so pushing before subscription would drop the event. + */ + private suspend fun awaitChange(app: KiloBackendAppService, push: () -> Unit): SessionChangeDto = + withTimeout(10_000) { + val ready = CompletableDeferred() + val change = scope.async { + app.sessions.changes.onSubscription { ready.complete(Unit) }.first() + } + ready.await() + push() + change.await() + } + + /** One SSE `data:` frame, which must stay on a single line or the frame is truncated. */ + private fun lifecycle(type: String, id: String, dir: String): String = + """{"type":"$type","properties":{"sessionID":"$id","info":""" + + """{"id":"$id","projectID":"prj","directory":"$dir","title":"T","version":"1",""" + + """"time":{"created":1,"updated":2}}}}""" + // ------ Lifecycle ------ @Test @@ -161,6 +188,19 @@ class KiloBackendSessionManagerTest { assertTrue(path.contains("archived=false"), path) } + @Test + fun `recent narrows the worktree family to the current worktree`() = runBlocking { + val app = setup() + ready(app) + + app.sessions.recent("/repo/.kilo/worktrees/feature", 5) + + val path = mock.lastExperimentalSessionPath ?: error("missing experimental session request") + // current=true is what keeps a worktree chat from listing the main checkout's sessions. + assertTrue(path.contains("current=true"), path) + assertFalse(path.contains("current=false"), path) + } + @Test fun `recent filters statuses to returned sessions`() = runBlocking { mock.recentSessions = """[ @@ -438,6 +478,61 @@ class KiloBackendSessionManagerTest { assertEquals("idle", app.sessions.statuses.value["ses_x"]?.type) } + // ------ SSE session lifecycle tracking ------ + + @Test + fun `SSE session created is republished on changes`() = runBlocking { + val app = setup() + ready(app) + mock.awaitSseConnection() + + val result = awaitChange(app) { + mock.pushEvent("session.created", lifecycle("session.created", "ses_live", "/repo/wt")) + } + + assertEquals("ses_live", result.id) + assertEquals("/repo/wt", result.directory) + assertEquals(SessionChangeKindDto.CREATED, result.kind) + } + + @Test + fun `SSE session lifecycle records and clears the directory for activity lookups`() = runBlocking { + val app = setup() + ready(app) + mock.awaitSseConnection() + + // The change is published only after the directory is recorded, so awaiting the event is + // enough — no polling. A session this frame never listed must still resolve a directory, + // otherwise the Agent Manager worktree row cannot be badged. + awaitChange(app) { + mock.pushEvent("session.created", lifecycle("session.created", "ses_elsewhere", "/repo/wt")) + } + assertEquals("/repo/wt", app.sessions.sessionDirectory("ses_elsewhere")) + + awaitChange(app) { + mock.pushEvent("session.deleted", lifecycle("session.deleted", "ses_elsewhere", "/repo/wt")) + } + assertNull(app.sessions.sessionDirectory("ses_elsewhere")) + } + + @Test + fun `activity badges a session this frame only learned about from events`() = runBlocking { + val app = setup() + ready(app) + mock.awaitSseConnection() + + mock.pushEvent("session.created", lifecycle("session.created", "ses_other_frame", "/repo/wt")) + mock.pushEvent( + "session.status", + """{"type":"session.status","properties":{"sessionID":"ses_other_frame","status":{"type":"busy"}}}""", + ) + + val snap = withTimeout(10_000) { + app.activity.activity.first { it.containsKey("ses_other_frame") } + } + assertEquals("/repo/wt", snap["ses_other_frame"]?.directory) + } + @Test fun `seed populates status map from server`() = runBlocking { mock.sessionStatuses = """{ diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/cli/KiloCliDataParserTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/cli/KiloCliDataParserTest.kt index 6ade08fddbf8..e42e03c81ac2 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/cli/KiloCliDataParserTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/cli/KiloCliDataParserTest.kt @@ -20,6 +20,7 @@ import ai.kilocode.rpc.dto.PartSourceTextDto import ai.kilocode.rpc.dto.PromptDto import ai.kilocode.rpc.dto.PromptPartDto import ai.kilocode.rpc.dto.QuestionReplyDto +import ai.kilocode.rpc.dto.SessionChangeKindDto import ai.kilocode.rpc.dto.SkillsPatchDto import ai.kilocode.rpc.dto.WatcherPatchDto import org.junit.jupiter.api.Nested @@ -1118,6 +1119,76 @@ class KiloCliDataParserTest { assertEquals("req_xyz", result.second.requestID) } + // ---- parseSessionChange ---- + + @Test + fun `parseSessionChange - created carries the session directory`() { + val data = sessionLifecycle("session.created", "ses_new", "/repo/.kilo/worktrees/feature", "Fix the bug") + val result = KiloCliDataParser.parseSessionChange("session.created", data) + assertNotNull(result) + assertEquals("ses_new", result.id) + assertEquals("/repo/.kilo/worktrees/feature", result.directory) + assertEquals(SessionChangeKindDto.CREATED, result.kind) + } + + @Test + fun `parseSessionChange - updated and deleted map to their kinds`() { + val updated = KiloCliDataParser.parseSessionChange( + "session.updated", + sessionLifecycle("session.updated", "ses_1", "/repo", "Renamed"), + ) + val deleted = KiloCliDataParser.parseSessionChange( + "session.deleted", + sessionLifecycle("session.deleted", "ses_1", "/repo", "Renamed"), + ) + assertEquals(SessionChangeKindDto.UPDATED, updated?.kind) + assertEquals(SessionChangeKindDto.DELETED, deleted?.kind) + } + + @Test + fun `parseSessionChange - falls back to the info id when sessionID is absent`() { + val data = globalEvent(""" + "type": "session.created", + "properties": { + "info": { "id": "ses_from_info", "directory": "/repo", "title": "T" } + } + """) + assertEquals("ses_from_info", KiloCliDataParser.parseSessionChange("session.created", data)?.id) + } + + @Test + fun `parseSessionChange - ignores unrelated types and unusable payloads`() { + // Wrong event type. + assertNull( + KiloCliDataParser.parseSessionChange( + "session.status", + sessionLifecycle("session.status", "ses_1", "/repo", "T"), + ), + ) + // No directory to scope on. + assertNull( + KiloCliDataParser.parseSessionChange( + "session.created", + globalEvent(""" + "type": "session.created", + "properties": { "info": { "id": "ses_1", "title": "T" } } + """), + ), + ) + // No info at all. + assertNull( + KiloCliDataParser.parseSessionChange( + "session.created", + globalEvent(""" + "type": "session.created", + "properties": { "sessionID": "ses_1" } + """), + ), + ) + // Malformed JSON. + assertNull(KiloCliDataParser.parseSessionChange("session.created", "not json")) + } + // ---- parsePermissionRequests / parseQuestionRequests ---- @Test @@ -2794,6 +2865,21 @@ class KiloCliDataParserTest { private fun globalEvent(payload: String): String = """{"directory":"/tmp","payload":{$payload}}""" + private fun sessionLifecycle(type: String, id: String, dir: String, title: String): String = globalEvent(""" + "type": "$type", + "properties": { + "sessionID": "$id", + "info": { + "id": "$id", + "projectID": "prj", + "directory": "$dir", + "title": "$title", + "version": "1", + "time": { "created": 1.0, "updated": 2.0 } + } + } + """) + private fun messageUpdated(id: String, role: String): String = globalEvent(""" "type": "message.updated", "properties": { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionListController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionListController.kt index d2ad69afab0f..d4a5405a16f5 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionListController.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionListController.kt @@ -8,6 +8,11 @@ import ai.kilocode.rpc.dto.SessionDto import com.intellij.ui.CollectionListModel import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.launch class WorktreeSessionListController( @@ -18,6 +23,28 @@ class WorktreeSessionListController( ) { val model = CollectionListModel() + /** Coalescing hop: many session changes in, at most one reload per quiet period out. */ + private val pings = MutableSharedFlow(extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) + + init { + // A session started in another project frame only reaches this list through the CLI's + // event stream — nothing local fires, so without this the row never appears until the tab + // is reopened. + cs.launch { + service.changes + .filter { normalizeWorktreePath(it.directory) == normalizeWorktreePath(dir) } + .collect { pings.emit(Unit) } + } + cs.launch { + // collectLatest restarts the delay on every new ping, so a streaming title (one + // session.updated per delta) costs one reload, not one per event. + pings.collectLatest { + delay(COALESCE_MS) + reload() + } + } + } + /** Snapshot of the listed sessions, in model order. */ @RequiresEdt fun sessions(): List = (0 until model.size).map { model.getElementAt(it) } @@ -119,6 +146,7 @@ class WorktreeSessionListController( companion object { private val LOG = KiloLog.create(WorktreeSessionListController::class.java) + private const val COALESCE_MS = 300L } private fun capture(event: String, props: Map) { diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/app/KiloSessionService.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/app/KiloSessionService.kt index 1fe58712160d..0d1615644f2a 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/app/KiloSessionService.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/app/KiloSessionService.kt @@ -19,6 +19,7 @@ import ai.kilocode.rpc.dto.PromptDto import ai.kilocode.rpc.dto.QuestionReplyDto import ai.kilocode.rpc.dto.QuestionRequestDto import ai.kilocode.rpc.dto.SessionActivityDto +import ai.kilocode.rpc.dto.SessionChangeDto import ai.kilocode.rpc.dto.SessionDto import ai.kilocode.rpc.dto.SessionListDto import ai.kilocode.rpc.dto.SessionStatusDto @@ -75,6 +76,13 @@ class KiloSessionService internal constructor( val activity: StateFlow> = stream { activity() }.stateIn(cs, SharingStarted.Eagerly, emptyMap()) + /** + * Session create/update/delete across every directory the CLI serves, including sessions + * started in another project frame. Consumers filter by directory and must coalesce: a single + * turn produces many `session.updated` events as the title and summary stream in. + */ + val changes: Flow = stream { changes() } + // ------ RPC helpers ------ private suspend fun call(block: suspend KiloSessionRpcApi.() -> T): T { @@ -119,7 +127,7 @@ class KiloSessionService internal constructor( */ suspend fun sessionsFor(dir: String): SessionListDto = call { list(dir) } - /** Load recent sessions for the current worktree family. */ + /** Load recent sessions for the worktree containing [dir]; sibling worktrees are excluded. */ suspend fun recent(dir: String, limit: Int): List = call { recent(dir, limit) }.sessions diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/controller/SessionController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/controller/SessionController.kt index 1ddcdde6209e..d64c4c776738 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/controller/SessionController.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/controller/SessionController.kt @@ -72,6 +72,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.launch import java.awt.Component import java.nio.file.Path @@ -1044,6 +1045,18 @@ class SessionController( } } } + + // Sessions started elsewhere — another editor tab, or another project frame opened on this + // same directory — only reach the empty state through the CLI's event stream. + cs.launch { + sessions.changes + .filter { it.directory == directory } + .collect { + edt { + if (canUseRecents()) refreshRecents(force = true) + } + } + } } private fun loadSession(token: SessionLoadState.Loading) { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionListControllerTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionListControllerTest.kt index 36f1c64ca38c..cf0e98228188 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionListControllerTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionListControllerTest.kt @@ -5,12 +5,22 @@ import ai.kilocode.client.testing.FakeSessionRpcApi import ai.kilocode.client.testing.TestCoroutines import ai.kilocode.client.testing.pumpEdt import ai.kilocode.client.util.edtWait +import ai.kilocode.rpc.dto.SessionChangeDto +import ai.kilocode.rpc.dto.SessionChangeKindDto import ai.kilocode.rpc.dto.SessionDto import ai.kilocode.rpc.dto.SessionTimeDto import com.intellij.testFramework.fixtures.BasePlatformTestCase @Suppress("UnstableApiUsage") class WorktreeSessionListControllerTest : BasePlatformTestCase() { + private companion object { + /** + * How long to keep pumping while proving a reload never happens. Must comfortably exceed + * the controller's change-coalescing window; positive waits use the shared default deadline. + */ + const val QUIET_MS = 1_500L + } + private lateinit var coroutines: TestCoroutines private lateinit var rpc: FakeSessionRpcApi private lateinit var sessions: KiloSessionService @@ -134,6 +144,59 @@ class WorktreeSessionListControllerTest : BasePlatformTestCase() { assertEquals("Old", controller.session("ses_1")?.title) } + fun `test a session change in this directory brings in the new session`() { + rpc.listed += session("ses_1", "One") + controller.reload() + drain() + val before = rpc.lists.size + + // A session started elsewhere in this worktree, then two title updates as it streams. The + // burst is emitted back to back so the coalescing window sees it as one. + rpc.listed += session("ses_from_other_frame", "Elsewhere") + emit( + change("ses_from_other_frame", dir, SessionChangeKindDto.CREATED), + change("ses_from_other_frame", dir, SessionChangeKindDto.UPDATED), + change("ses_from_other_frame", dir, SessionChangeKindDto.UPDATED), + ) + + assertTrue(coroutines.pumpUntil { controller.session("ses_from_other_frame") != null }) + // Coalesced: a burst costs one reload, not one per event. + assertEquals(1, rpc.lists.size - before) + } + + fun `test a session change in another directory is ignored`() { + controller.reload() + drain() + val before = rpc.lists.size + + emit(change("ses_main", "/repo", SessionChangeKindDto.CREATED)) + // Waiting past the coalescing window proves no reload was merely pending. + assertFalse(coroutines.pumpUntil(QUIET_MS) { rpc.lists.size > before }) + } + + fun `test a session change matches a directory with a trailing separator`() { + controller.reload() + drain() + val before = rpc.lists.size + + emit(change("ses_1", "$dir/", SessionChangeKindDto.CREATED)) + + assertTrue(coroutines.pumpUntil { rpc.lists.size > before }) + } + + /** + * Emits into the fake's change flow from a background thread. The flow has no replay, so the + * controller's collector must already be subscribed — every caller reloads and drains first. + */ + private fun emit(vararg values: SessionChangeDto) { + kotlinx.coroutines.runBlocking(kotlinx.coroutines.Dispatchers.Default) { + values.forEach { rpc.changes.emit(it) } + } + } + + private fun change(id: String, directory: String, kind: SessionChangeKindDto) = + SessionChangeDto(id, directory, kind) + private fun session(id: String, title: String) = SessionDto( id = id, projectID = "prj", diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/controller/SessionControllerTestBase.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/controller/SessionControllerTestBase.kt index 0e280ec37d9d..1424560cf62f 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/controller/SessionControllerTestBase.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/controller/SessionControllerTestBase.kt @@ -29,6 +29,8 @@ import ai.kilocode.rpc.dto.ModelDto import ai.kilocode.rpc.dto.PartDto import ai.kilocode.rpc.dto.ProviderDto import ai.kilocode.rpc.dto.ProvidersDto +import ai.kilocode.rpc.dto.SessionChangeDto +import ai.kilocode.rpc.dto.SessionChangeKindDto import ai.kilocode.rpc.dto.SessionDto import ai.kilocode.rpc.dto.SessionTimeDto import ai.kilocode.rpc.dto.TelemetryCaptureDto @@ -36,6 +38,7 @@ import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Disposer import com.intellij.testFramework.fixtures.BasePlatformTestCase +import ai.kilocode.client.testing.TEST_WAIT_MS import ai.kilocode.client.testing.pumpEdt import java.awt.event.HierarchyEvent import kotlinx.coroutines.CoroutineScope @@ -276,6 +279,19 @@ abstract class SessionControllerTestBase : BasePlatformTestCase() { if (flush) flush() } + /** Emit a session lifecycle change into the fake RPC flow. */ + protected fun change(id: String, directory: String, kind: SessionChangeKindDto) { + runBlocking { rpc.changes.emit(SessionChangeDto(id, directory, kind)) } + } + + /** + * Drain background work and the EDT until [cond] holds, returning whether it did. Use for state + * that arrives from a flow rather than from a call the test just made, where [flush] alone + * cannot know how many hops are still pending. + */ + protected fun waitFor(deadlineMs: Long = TEST_WAIT_MS, cond: () -> Boolean): Boolean = + coroutines.pumpUntil(deadlineMs, { edt { controllers.forEach { it.flushEvents() } }; pumpEdt() }, cond) + /** Create a controller, attach both listeners, send initial prompt, and flush. */ protected fun prompted(): Triple, MutableList> { appRpc.state.value = KiloAppStateDto(KiloAppStatusDto.READY, config = ConfigDto(model = "kilo/gpt-5")) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/controller/ViewSwitchingTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/controller/ViewSwitchingTest.kt index 87c8bafbb635..00710b9de3e0 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/controller/ViewSwitchingTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/controller/ViewSwitchingTest.kt @@ -9,9 +9,14 @@ import ai.kilocode.rpc.dto.MessageWithPartsDto import ai.kilocode.rpc.dto.ProfileBalanceDto import ai.kilocode.rpc.dto.ProfileDto import ai.kilocode.rpc.dto.ProfileOrganizationDto +import ai.kilocode.rpc.dto.SessionChangeKindDto import kotlinx.coroutines.CompletableDeferred class ViewSwitchingTest : SessionControllerTestBase() { + private companion object { + /** How long to keep draining while proving a recents refresh never happens. */ + const val QUIET_MS = 1_000L + } fun `test first prompt shows messages view`() { val m = controller() @@ -99,6 +104,52 @@ class ViewSwitchingTest : SessionControllerTestBase() { assertTrue(m.recents().isEmpty()) } + fun `test session change in this directory refreshes recents`() { + projectRpc.state.value = workspaceReady() + rpc.recent.add(session("ses_1")) + val m = controller() + collect(m) + flush() + assertEquals(1, rpc.recentCalls.size) + + // A session created elsewhere for the same directory — another editor tab, or another IDE + // frame opened on this worktree. + rpc.recent.add(session("ses_2")) + change("ses_2", "/test", SessionChangeKindDto.CREATED) + + assertTrue(waitFor { rpc.recentCalls.size > 1 }) + assertEquals(2, m.recents().size) + } + + fun `test session change in another directory does not refresh recents`() { + projectRpc.state.value = workspaceReady() + rpc.recent.add(session("ses_1")) + val m = controller() + collect(m) + flush() + assertEquals(1, rpc.recentCalls.size) + + change("ses_other", "/repo/.kilo/worktrees/other", SessionChangeKindDto.CREATED) + + assertFalse(waitFor(QUIET_MS) { rpc.recentCalls.size > 1 }) + assertEquals(1, m.recents().size) + } + + fun `test session change does not refresh recents while a session is open`() { + projectRpc.state.value = workspaceReady() + rpc.recent.add(session("ses_1")) + val m = controller("ses_test") + collect(m) + flush() + assertTrue(rpc.recentCalls.isEmpty()) + + change("ses_test", "/test", SessionChangeKindDto.UPDATED) + + // The empty state is not showing, so recents must stay untouched. + assertFalse(waitFor(QUIET_MS) { rpc.recentCalls.isNotEmpty() }) + assertTrue(m.recents().isEmpty()) + } + fun `test empty explicit session history shows empty view`() { rpc.recent.add(session("ses_1")) val m = controller("ses_test", displayMs = 1_000) diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeSessionRpcApi.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeSessionRpcApi.kt index 7b474387fd0a..d924f906fcf3 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeSessionRpcApi.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/testing/FakeSessionRpcApi.kt @@ -17,6 +17,7 @@ import ai.kilocode.rpc.dto.QuestionReplyDto import ai.kilocode.rpc.dto.QuestionRequestDto import ai.kilocode.rpc.dto.SessionDto import ai.kilocode.rpc.dto.SessionActivityDto +import ai.kilocode.rpc.dto.SessionChangeDto import ai.kilocode.rpc.dto.SessionListDto import ai.kilocode.rpc.dto.SessionStatusDto import ai.kilocode.rpc.dto.SessionTimeDto @@ -77,6 +78,9 @@ class FakeSessionRpcApi : KiloSessionRpcApi { /** Push activity updates here. */ val activity = MutableStateFlow>(emptyMap()) + /** Push session lifecycle changes here. */ + val changes = MutableSharedFlow(extraBufferCapacity = 64) + /** Pending permissions returned by [pendingPermissions]. */ val pendingPermissionList = mutableListOf() @@ -205,6 +209,11 @@ class FakeSessionRpcApi : KiloSessionRpcApi { return activity } + override suspend fun changes(): Flow { + assertNotEdt("changes") + return changes + } + override suspend fun setDirectory(id: String, directory: String) { assertNotEdt("setDirectory") } diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloSessionRpcApi.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloSessionRpcApi.kt index ae3851c2b2e4..557b4c358ca3 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloSessionRpcApi.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloSessionRpcApi.kt @@ -15,6 +15,7 @@ import ai.kilocode.rpc.dto.QuestionReplyDto import ai.kilocode.rpc.dto.QuestionRequestDto import ai.kilocode.rpc.dto.SessionDto import ai.kilocode.rpc.dto.SessionActivityDto +import ai.kilocode.rpc.dto.SessionChangeDto import ai.kilocode.rpc.dto.SessionListDto import ai.kilocode.rpc.dto.SessionStatusDto import com.intellij.platform.rpc.RemoteApiProviderService @@ -42,7 +43,7 @@ interface KiloSessionRpcApi : RemoteApi { /** List root sessions for a directory. */ suspend fun list(directory: String): SessionListDto - /** List recent root sessions for the current worktree family. */ + /** List recent root sessions for the worktree containing [directory]. */ suspend fun recent(directory: String, limit: Int): SessionListDto /** Create a new session in the given directory. */ @@ -69,6 +70,12 @@ interface KiloSessionRpcApi : RemoteApi { /** Observe live per-session activity with the session's directory. */ suspend fun activity(): Flow> + /** + * Observe session create/update/delete across every directory this CLI serves, so a + * directory-scoped list can refresh when a session is started in another project frame. + */ + suspend fun changes(): Flow + /** Register a worktree directory override for a session. */ suspend fun setDirectory(id: String, directory: String) diff --git a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/SessionDto.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/SessionDto.kt index 92f2eccf2241..31105ba13045 100644 --- a/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/SessionDto.kt +++ b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/dto/SessionDto.kt @@ -67,3 +67,24 @@ data class SessionListDto( val sessions: List, val statuses: Map, ) + +@Serializable +enum class SessionChangeKindDto { + CREATED, + UPDATED, + DELETED, +} + +/** + * A session lifecycle change observed on the CLI event stream, tagged with the session's own + * directory so directory-scoped views can decide whether it concerns them. + * + * The stream is app-wide: it carries changes for every directory this IDE's CLI serves, including + * sessions started in another project frame. + */ +@Serializable +data class SessionChangeDto( + val id: String, + val directory: String, + val kind: SessionChangeKindDto, +) From d24cedd170353033b7886ed27359c378f0990df5 Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 14:52:16 -0400 Subject: [PATCH 28/30] fix(jetbrains): align chat PR badge --- .../jetbrains-chat-pr-badge-alignment.md | 5 ++ .../worktree/WorktreePrHeaderView.kt | 2 +- .../client/session/ui/header/BranchDock.kt | 8 ++- .../client/session/ui/header/PrHeaderView.kt | 8 ++- .../session/ui/header/BranchDockTest.kt | 58 +++++++++++++++++++ .../session/ui/header/PrHeaderViewTest.kt | 17 ++++++ 6 files changed, 91 insertions(+), 7 deletions(-) create mode 100644 .changeset/jetbrains-chat-pr-badge-alignment.md diff --git a/.changeset/jetbrains-chat-pr-badge-alignment.md b/.changeset/jetbrains-chat-pr-badge-alignment.md new file mode 100644 index 000000000000..c7638a8ce1ee --- /dev/null +++ b/.changeset/jetbrains-chat-pr-badge-alignment.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Use regular PR title text and vertically center the PR badge in the JetBrains chat tool window. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt index dcce0e600d31..af87c6f80ca1 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt @@ -21,7 +21,7 @@ internal class WorktreePrHeaderView( openTerminal: () -> Unit = {}, openDiff: () -> Unit, ) : BorderLayoutPanel() { - private val core = PrHeaderView(openDiff) + private val core = PrHeaderView(openDiff = openDiff) private val terminal = hoverTextButton( ToolbarButtonAction(TerminalIcons.OpenTerminal_13x13, KiloBundle.message("worktree.session.terminal.action"), openTerminal), tooltip = KiloBundle.message("worktree.session.terminal.tooltip"), diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt index bdc2e6a88f96..22ebc4080ca2 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.kt @@ -17,6 +17,7 @@ import com.intellij.openapi.actionSystem.DataSink import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.UiDataProvider import com.intellij.openapi.application.ApplicationManager +import com.intellij.ui.SimpleTextAttributes import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel @@ -43,8 +44,9 @@ internal class BranchDock( openDiff: () -> Unit, private val onMove: (() -> Unit)?, private val onNewWorktree: (() -> Unit)? = null, + titleStyle: Int = SimpleTextAttributes.STYLE_PLAIN, ) : BorderLayoutPanel(), SessionEditorStyleTarget, UiDataProvider { - private val core = PrHeaderView(openDiff) + private val core = PrHeaderView(titleStyle = titleStyle, openDiff = openDiff) private val changes = BranchChangesBadge(openDiff) private val group = DefaultActionGroup().apply { ActionManager.getInstance().getAction("Kilo.Chat.NewWorktree")?.let { add(it) } @@ -66,7 +68,7 @@ internal class BranchDock( toolbar.targetComponent = this // Transparent so the toolbar shows the dock's prompt-matching background and tracks LaF. toolbar.component.isOpaque = false - addToCenter(Stack.vertical().next(core).next(actionRow)) + addToCenter(Stack.vertical().next(core).next(actionRow).align(HAlign.TRACK, VAlign.CENTER)) isVisible = false sync() } @@ -77,7 +79,7 @@ internal class BranchDock( super.updateUI() border = JBUI.Borders.compound( JBUI.Borders.customLineTop(JBUI.CurrentTheme.EditorTabs.borderColor()), - JBUI.Borders.empty(0, 0), + JBUI.Borders.empty(), ) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt index b570e35d3caa..eec87f1dcffe 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt @@ -36,6 +36,7 @@ import java.awt.event.MouseEvent * Stays non-opaque so the host owns background and borders. */ internal class PrHeaderView( + private val titleStyle: Int = SimpleTextAttributes.STYLE_BOLD, openDiff: () -> Unit, ) : BorderLayoutPanel(), SessionEditorStyleTarget { private val status = JBLabel() @@ -165,10 +166,11 @@ internal class PrHeaderView( val number = number ?: return title.clear() val body = body + val attrs = SimpleTextAttributes(titleStyle, UIUtil.getLabelForeground()) if (body == null) { - title.append(number, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) + title.append(number, attrs) } else { - title.append(body, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) + title.append(body, attrs) title.append(" $number", SimpleTextAttributes.GRAYED_ATTRIBUTES) } } @@ -184,7 +186,7 @@ internal class PrHeaderView( override fun applyStyle(style: SessionEditorStyle) { this.style = style changes.applyStyle(style) - // Re-render the title so its bold foreground follows the theme, then repaint. + // Re-render the title so its foreground follows the theme, then repaint. renderTitle() changed() } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt index 18435743d069..517ffc7d1823 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt @@ -3,6 +3,7 @@ package ai.kilocode.client.session.ui.header import ai.kilocode.client.actions.ChatMoveToWorktreeAction import ai.kilocode.client.actions.ChatNewWorktreeAction import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.ui.FilledBadgeIcon import ai.kilocode.client.util.edtWait import ai.kilocode.rpc.dto.BranchStatusDto import ai.kilocode.rpc.dto.DiffFileDto @@ -15,6 +16,13 @@ import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.testFramework.fixtures.BasePlatformTestCase +import com.intellij.ui.SimpleColoredComponent +import com.intellij.ui.SimpleTextAttributes +import com.intellij.ui.components.JBLabel +import java.awt.Component +import java.awt.Container +import java.awt.Point +import javax.swing.SwingUtilities @Suppress("UnstableApiUsage") class BranchDockTest : BasePlatformTestCase() { @@ -71,6 +79,27 @@ class BranchDockTest : BasePlatformTestCase() { assertTrue(edt { dock.isVisible }) } + fun `test PR title uses normal text in the tool window dock`() { + val dock = dock() + edt { dock.setBranch(prBranch()) } + + val title = edt { components(dock).filterIsInstance().single() } + assertEquals(SimpleTextAttributes.STYLE_PLAIN, edt { firstAttrs(title).style }) + } + + fun `test PR state badge is vertically centered in the reserved dock row`() { + val dock = dock() + edt { + dock.setBranch(prBranch()) + dock.setSize(500, dock.preferredSize.height) + layout(dock) + } + + val badge = edt { components(dock).filterIsInstance().single { it.icon is FilledBadgeIcon } } + val center = edt { SwingUtilities.convertPoint(badge, Point(0, 0), dock).y + badge.height / 2 } + assertTrue(kotlin.math.abs(edt { dock.height / 2 } - center) <= 1) + } + // ---- active session ---- fun `test dock hidden while session is busy`() { @@ -257,6 +286,35 @@ class BranchDockTest : BasePlatformTestCase() { private fun dockWithNewWorktree(): BranchDock = edt { BranchDock(openDiff = {}, onMove = {}, onNewWorktree = {}) } + private fun prBranch() = BranchStatusDto( + branch = "feature-x", + worktree = true, + availability = GhAvailability.OK, + pr = WorktreePrDto("/repo", 7, GhState.OPEN, "https://pr/7", "Title"), + ) + + private fun firstAttrs(title: SimpleColoredComponent): SimpleTextAttributes { + val iter = title.iterator() + check(iter.hasNext()) { "missing title fragment" } + iter.next() + return iter.textAttributes + } + + private fun layout(root: Component) { + root.doLayout() + if (root is Container) root.components.forEach(::layout) + } + + private fun components(root: Component): List { + val out = mutableListOf() + fun visit(item: Component) { + out += item + if (item is Container) item.components.forEach { visit(it) } + } + visit(root) + return out + } + private fun update(action: AnAction, dock: BranchDock): Presentation { val event = event(action, dock) edt { ActionUtil.updateAction(action, event) } diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt index 1743071d0e46..8c39ba9bdc7e 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt @@ -10,6 +10,7 @@ import ai.kilocode.rpc.dto.WorktreePrDto import ai.kilocode.rpc.dto.WorktreeStatsDto import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.ui.SimpleColoredComponent +import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.JBLabel import com.intellij.util.ui.UIUtil import java.awt.Component @@ -31,6 +32,15 @@ class PrHeaderViewTest : BasePlatformTestCase() { assertEquals(Cursor.HAND_CURSOR, edt { title.cursor.type }) } + fun `test title style can be configured`() { + val view = edt { PrHeaderView(openDiff = {}, titleStyle = SimpleTextAttributes.STYLE_PLAIN) } + + edt { view.update(files = 0, additions = 0, deletions = 0, pull = pull(GhState.OPEN), name = "feature-x") } + + val title = edt { title(view) } + assertEquals(SimpleTextAttributes.STYLE_PLAIN, edt { firstAttrs(title).style }) + } + fun `test no PR hides badge and title`() { val view = edt { PrHeaderView {} } @@ -112,6 +122,13 @@ class PrHeaderViewTest : BasePlatformTestCase() { return out } + private fun firstAttrs(title: SimpleColoredComponent): SimpleTextAttributes { + val iter = title.iterator() + check(iter.hasNext()) { "missing title fragment" } + iter.next() + return iter.textAttributes + } + private fun components(root: Component): List { val out = mutableListOf() fun visit(item: Component) { From e9f56d48afb1a9117f102ebfd680077012af1452 Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 15:33:57 -0400 Subject: [PATCH 29/30] fix(jetbrains): keep header popups beside chat --- .../jetbrains-chat-popup-orientation.md | 5 + .../client/session/ui/popup/HeaderPopup.kt | 29 +++- .../session/ui/popup/HeaderPopupController.kt | 53 ++++++- .../session/ui/popup/HeaderPopupGeometry.kt | 70 +++++++++ .../kotlin/ai/kilocode/client/ui/UiStyle.kt | 17 +++ .../session/ui/popup/HeaderPopupBodyTest.kt | 30 ++++ .../ui/popup/HeaderPopupGeometryTest.kt | 139 ++++++++++++++++++ 7 files changed, 337 insertions(+), 6 deletions(-) create mode 100644 .changeset/jetbrains-chat-popup-orientation.md create mode 100644 packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupGeometry.kt create mode 100644 packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupGeometryTest.kt diff --git a/.changeset/jetbrains-chat-popup-orientation.md b/.changeset/jetbrains-chat-popup-orientation.md new file mode 100644 index 000000000000..3d82a8f8e1b9 --- /dev/null +++ b/.changeset/jetbrains-chat-popup-orientation.md @@ -0,0 +1,5 @@ +--- +"@kilocode/kilo-jetbrains": patch +--- + +Keep session header popups beside the chat by choosing the roomier left or right side and sizing them so IntelliJ does not flip them above or below. diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopup.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopup.kt index d827983edc30..917b3e59d260 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopup.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopup.kt @@ -35,7 +35,18 @@ class HeaderPopupBody( fixedHeight: Boolean = false, horizontal: Boolean = false, ) { - val component: JComponent = HeaderPopupPanel(component, JBUI.scale(maxWidth), minWidth, fixedHeight, horizontal) + private val panel = HeaderPopupPanel(component, JBUI.scale(maxWidth), minWidth, fixedHeight, horizontal) + + val component: JComponent get() = panel + + /** + * Clamps the body to the space available beside the chat, in already-scaled device px. This wins + * over the opt-in floor width, because a body that overflows its side makes the balloon re-point + * above or below the chat. + */ + fun fitWithin(width: Int, height: Int) { + panel.fitWithin(width, height) + } } private class HeaderPopupPanel( @@ -45,6 +56,9 @@ private class HeaderPopupPanel( private val fixedHeight: Boolean, horizontal: Boolean, ) : JPanel(BorderLayout()) { + private var capWidth = Int.MAX_VALUE + private var capHeight = Int.MAX_VALUE + // One scroll pane wraps every popup body (single-file edit, multi-file patch, session changes), // so bodies taller than the max height scroll instead of clipping. Bodies that carry their own // inner scroll pane render at full height inside the viewport, so only this outer pane scrolls. @@ -64,11 +78,18 @@ private class HeaderPopupPanel( add(scroll, BorderLayout.CENTER) } + fun fitWithin(width: Int, height: Int) { + capWidth = width + capHeight = height + invalidate() + } + override fun getPreferredSize(): Dimension { - val measured = contentWidth(child).takeIf { it > 0 }?.coerceAtMost(maxWidth) ?: maxWidth - val width = measured.coerceAtLeast(minWidth).coerceAtMost(maxWidth) + val limit = minOf(maxWidth, capWidth) + val measured = contentWidth(child).takeIf { it > 0 }?.coerceAtMost(limit) ?: limit + val width = measured.coerceAtLeast(minOf(minWidth, limit)).coerceAtMost(limit) fit(child, width) - val cap = JBUI.scale(SessionUiStyle.View.Popup.MAX_HEIGHT) + val cap = minOf(JBUI.scale(SessionUiStyle.View.Popup.MAX_HEIGHT), capHeight) val height = if (fixedHeight) cap else child.preferredSize.height.coerceAtMost(cap) return Dimension(width, height) } diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupController.kt index 5c3290e2d767..7995bb512950 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupController.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupController.kt @@ -1,5 +1,7 @@ package ai.kilocode.client.session.ui.popup +import ai.kilocode.client.session.ui.SessionRootPanel +import ai.kilocode.client.session.ui.style.SessionUiStyle import ai.kilocode.client.session.views.base.PartView import ai.kilocode.client.ui.UiStyle import ai.kilocode.client.util.UiTimerSource @@ -10,11 +12,16 @@ import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.Disposer +import com.intellij.ui.ComponentUtil import com.intellij.ui.awt.RelativePoint import com.intellij.ui.hover.HoverListener import com.intellij.util.concurrency.annotations.RequiresEdt +import com.intellij.util.ui.JBUI import java.awt.Component import java.awt.Point +import java.awt.Rectangle +import javax.swing.JComponent +import javax.swing.SwingUtilities /** * Shows a single header popup after a short hover dwell and hides it after a short grace period. @@ -113,6 +120,11 @@ class HeaderPopupController(timers: UiTimerSource = UiTimers) : Disposable { if (!onHeader && !onPopup) return hideAll() val req = view.headerPopup() ?: return hideAll() val built = req.build() + place(req.anchor, built)?.let { open(req, built, it) } ?: hideAll() + } + + @RequiresEdt + private fun open(req: HeaderPopupRequest, built: HeaderPopupBody, spot: Spot) { val popup = JBPopupFactory.getInstance() .createBalloonBuilder(built.component) .setFillColor(built.background) @@ -143,11 +155,48 @@ class HeaderPopupController(timers: UiTimerSource = UiTimers) : Disposable { balloon = popup body = built.disposable - val point = RelativePoint(req.anchor, Point(req.anchor.width, req.anchor.height / 2)) - popup.show(point, Balloon.Position.atRight) + popup.show(RelativePoint(spot.pane, spot.point), spot.position) req.shown() } + /** + * Resolves the pointer target beside the session chat, sizing the body to the space available on + * the chosen side. Anchoring on the chat rather than the hovered row is what keeps the popup off + * the transcript instead of covering the row the user is reading. + * + * Returns null when the chat is not on screen yet, in which case there is nothing to sit beside. + */ + @RequiresEdt + private fun place(anchor: JComponent, built: HeaderPopupBody): Spot? { + val pane = SwingUtilities.getRootPane(anchor)?.layeredPane + val chat = ComponentUtil.getParentOfType(SessionRootPanel::class.java, anchor) + // A showing anchor implies every ancestor, including the chat, is showing and laid out. + if (pane == null || chat == null || !anchor.isShowing) return null + val gap = UiStyle.Gap.pad() + val insets = UiStyle.Balloon.insets() + // The shadow is reserved on every side, so it counts twice on each axis. + val shadow = UiStyle.Balloon.shadow() * 2 + val chromeHeight = insets.top + insets.bottom + shadow + val bounds = Rectangle(pane.size) + val spot = HeaderPopupGeometry.beside( + pane = bounds, + chat = SwingUtilities.convertRectangle(chat.parent, chat.bounds, pane), + fit = HeaderPopupFit( + chromeWidth = insets.left + insets.right + UiStyle.Balloon.pointer().height + shadow, + chromeHeight = chromeHeight, + gap = gap, + maxWidth = JBUI.scale(SessionUiStyle.View.Popup.WIDE_MAX_WIDTH), + maxHeight = JBUI.scale(SessionUiStyle.View.Popup.MAX_HEIGHT), + ), + ) + built.fitWithin(spot.maxWidth, spot.maxHeight) + val row = SwingUtilities.convertPoint(anchor, Point(0, anchor.height / 2), pane) + val height = built.component.preferredSize.height + chromeHeight + return Spot(pane, Point(spot.x, HeaderPopupGeometry.centerY(bounds, row.y, height, gap)), spot.position) + } + + private class Spot(val pane: JComponent, val point: Point, val position: Balloon.Position) + private companion object { const val SHOW_MS = 500 const val HIDE_MS = 250 diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupGeometry.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupGeometry.kt new file mode 100644 index 000000000000..6a790e9b3d68 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupGeometry.kt @@ -0,0 +1,70 @@ +package ai.kilocode.client.session.ui.popup + +import com.intellij.openapi.ui.popup.Balloon +import java.awt.Rectangle + +/** + * Where a header popup should sit relative to the session chat, and how large its body may be. + * + * [x] is the pointer target in the same coordinate space the placement was computed in. + */ +internal data class HeaderPopupPlacement( + val position: Balloon.Position, + val x: Int, + val maxWidth: Int, + val maxHeight: Int, +) + +/** + * Room the balloon needs beyond its body. + * + * [chromeWidth] and [chromeHeight] are what the balloon adds around its content on each axis (border + * insets, pointer, and the drop shadow, which is the easy one to forget), [gap] is breathing room kept + * against the pane edges, and [maxWidth]/[maxHeight] are the shared body caps. + */ +internal data class HeaderPopupFit( + val chromeWidth: Int, + val chromeHeight: Int, + val gap: Int, + val maxWidth: Int, + val maxHeight: Int, +) + +/** + * Geometry for header popups. Pure functions so the side and fit rules are testable without a frame. + * + * Header popups only ever sit beside the chat, never over it and never above or below it. The fit part + * is not cosmetic: `BalloonImpl.show` silently re-points a balloon to `BELOW`/`ABOVE` when the + * requested rectangle does not fit inside the layered pane, so a body that overflows its side would + * land in exactly the placement we are avoiding. Capping the body keeps the requested position. + */ +internal object HeaderPopupGeometry { + + /** Picks the side of [chat] with more room inside [pane] and the body box that fits there. */ + fun beside(pane: Rectangle, chat: Rectangle, fit: HeaderPopupFit): HeaderPopupPlacement { + val left = (chat.x - pane.x).coerceAtLeast(0) + val right = (pane.x + pane.width - (chat.x + chat.width)).coerceAtLeast(0) + // Ties go right: it matches reading direction and the common tool-window-on-the-left setup. + val useRight = right >= left + val room = (if (useRight) right else left) - fit.chromeWidth - fit.gap + return HeaderPopupPlacement( + position = if (useRight) Balloon.Position.atRight else Balloon.Position.atLeft, + x = if (useRight) chat.x + chat.width else chat.x, + maxWidth = room.coerceIn(0, fit.maxWidth), + maxHeight = (pane.height - fit.gap * 2 - fit.chromeHeight).coerceIn(0, fit.maxHeight), + ) + } + + /** + * Vertical pointer target for a body of [height], preferring [y] but keeping the balloon inside + * [pane]. The balloon centres its body on the target, so an unclamped target near an edge would + * overflow and trigger the same re-pointing that [beside] avoids horizontally. + */ + fun centerY(pane: Rectangle, y: Int, height: Int, gap: Int): Int { + val half = height / 2 + val top = pane.y + gap + half + val bottom = pane.y + pane.height - gap - half + if (bottom < top) return pane.y + pane.height / 2 + return y.coerceIn(top, bottom) + } +} diff --git a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt index cc87182d10f5..bcdc6c16f35e 100644 --- a/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt @@ -3,6 +3,7 @@ package ai.kilocode.client.ui import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorColorsScheme +import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ColorUtil import com.intellij.ui.JBColor import com.intellij.util.ui.JBFont @@ -39,6 +40,9 @@ object UiStyle { /** Platform balloon styling used by lightweight contextual overlays. */ object Balloon { + /** Mirrors the platform default for `ide.balloon.shadow.size`, used only if the key is gone. */ + private const val SHADOW_SIZE = 24 + fun bg(): Color = UIUtil.getPanelBackground() fun border(): Color = JBUI.CurrentTheme.Popup.borderColor(true) @@ -49,6 +53,19 @@ object UiStyle { fun pointer() = JBUI.size(16, 8) fun arc() = JBUI.scale(8) + + /** + * Drop-shadow inset the platform reserves on every side of a balloon, or 0 when shadows are + * off. Read from the same registry keys `BalloonImpl` uses, because callers that size a + * balloon to fit an area have to account for it: an overflowing balloon is silently + * re-pointed to another side. + */ + fun shadow(): Int = + if (Registry.`is`("ide.balloon.shadowEnabled", true)) { + JBUI.scale(Registry.intValue("ide.balloon.shadow.size", SHADOW_SIZE)) + } else { + 0 + } } /** Filled badge styles shared across JetBrains UI surfaces. */ diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupBodyTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupBodyTest.kt index 2d866e53e7df..dea970bbc299 100644 --- a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupBodyTest.kt +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupBodyTest.kt @@ -37,6 +37,36 @@ class HeaderPopupBodyTest : BasePlatformTestCase() { assertEquals(JBUI.scale(40), body.component.preferredSize.height) } + fun `test fitWithin caps the body to the space beside the chat`() { + val wide = JPanel().apply { + preferredSize = Dimension( + JBUI.scale(SessionUiStyle.View.Popup.MAX_WIDTH), + JBUI.scale(SessionUiStyle.View.Popup.MAX_HEIGHT), + ) + } + val body = HeaderPopupBody(wide, owner(), UIUtil.getPanelBackground()) + + body.fitWithin(JBUI.scale(120), JBUI.scale(90)) + + assertEquals(JBUI.scale(120), body.component.preferredSize.width) + assertEquals(JBUI.scale(90), body.component.preferredSize.height) + } + + fun `test fitWithin wins over the opt-in floor width`() { + val wide = JPanel().apply { + preferredSize = Dimension(JBUI.scale(SessionUiStyle.View.Popup.MAX_WIDTH), JBUI.scale(80)) + } + // A body that asks for a floor width still has to fit its side, otherwise the balloon would + // re-point above or below the chat. + val body = HeaderPopupBody(wide, owner(), UIUtil.getPanelBackground(), minWidth = JBUI.scale(300)) + + body.fitWithin(JBUI.scale(100), JBUI.scale(400)) + + assertEquals(JBUI.scale(100), body.component.preferredSize.width) + } + + private fun owner() = Disposer.newDisposable("popup body").also { Disposer.register(testRootDisposable, it) } + private fun descendants(root: Component): List { val out = mutableListOf() fun visit(node: Component) { diff --git a/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupGeometryTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupGeometryTest.kt new file mode 100644 index 000000000000..2c4dec004fc8 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/popup/HeaderPopupGeometryTest.kt @@ -0,0 +1,139 @@ +package ai.kilocode.client.session.ui.popup + +import com.intellij.openapi.ui.popup.Balloon +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.awt.Rectangle + +class HeaderPopupGeometryTest { + private companion object { + const val CHROME = 30 + const val CHROME_HEIGHT = 60 + const val GAP = 10 + const val CAP = 700 + const val CAP_HEIGHT = 450 + } + + @Test + fun `chat on the left points right`() { + // Tool window on the left: the editor area to its right is the roomier side. + val spot = beside(chat = Rectangle(0, 0, 300, 1000)) + + assertEquals(Balloon.Position.atRight, spot.position) + assertEquals(300, spot.x) + } + + @Test + fun `chat on the right points left`() { + val spot = beside(chat = Rectangle(1700, 0, 300, 1000)) + + assertEquals(Balloon.Position.atLeft, spot.position) + assertEquals(1700, spot.x) + } + + @Test + fun `side with more room wins even when both sides fit`() { + val spot = beside(chat = Rectangle(1200, 0, 300, 1000)) + + // Left room is 1200, right room is 500. + assertEquals(Balloon.Position.atLeft, spot.position) + assertEquals(1200, spot.x) + } + + @Test + fun `equal room points right`() { + val spot = beside(chat = Rectangle(850, 0, 300, 1000)) + + assertEquals(Balloon.Position.atRight, spot.position) + } + + @Test + fun `body is capped to the free space on the chosen side`() { + val spot = beside(chat = Rectangle(0, 0, 1800, 1000)) + + // 200 free on the right, minus chrome and gap. + assertEquals(200 - CHROME - GAP, spot.maxWidth) + } + + @Test + fun `body is capped to the shared max when the side is roomy`() { + val spot = beside(chat = Rectangle(0, 0, 300, 1000)) + + assertEquals(CAP, spot.maxWidth) + } + + @Test + fun `a chat filling the pane yields no room rather than a negative width`() { + val spot = beside(chat = Rectangle(0, 0, 2000, 1000)) + + assertEquals(0, spot.maxWidth) + } + + @Test + fun `chrome is reserved so the balloon still fits its side`() { + // The side has 400px; a body of the full 400 would overflow once the balloon adds its border, + // pointer and shadow, and an overflowing balloon gets re-pointed above or below the chat. + val spot = beside(chat = Rectangle(0, 0, 1600, 1000)) + + assertTrue(spot.maxWidth + CHROME <= 400) + } + + @Test + fun `a chat with no usable room on either side still resolves to a horizontal side`() { + val tight = HeaderPopupGeometry.beside( + pane = Rectangle(0, 0, 2000, 1000), + chat = Rectangle(0, 0, 1980, 1000), + fit = fit(), + ) + + // Neither side can fit the chrome, but above/below must never be the answer. + assertTrue(tight.position == Balloon.Position.atRight || tight.position == Balloon.Position.atLeft) + assertEquals(0, tight.maxWidth) + } + + @Test + fun `height is capped to the pane minus gaps`() { + val short = HeaderPopupGeometry.beside( + pane = Rectangle(0, 0, 2000, 200), + chat = Rectangle(0, 0, 300, 200), + fit = fit(), + ) + + // 200 pane, minus both gaps and the chrome the balloon reserves vertically. + assertEquals(200 - GAP * 2 - CHROME_HEIGHT, short.maxHeight) + } + + @Test + fun `pointer target keeps a tall body inside the pane`() { + val pane = Rectangle(0, 0, 2000, 1000) + + // Row near the top: target pushed down so the centred body clears the top edge. + assertEquals(310, HeaderPopupGeometry.centerY(pane, y = 20, height = 600, gap = GAP)) + // Row near the bottom: target pulled up. + assertEquals(690, HeaderPopupGeometry.centerY(pane, y = 980, height = 600, gap = GAP)) + // Row with room on both sides is left alone. + assertEquals(500, HeaderPopupGeometry.centerY(pane, y = 500, height = 600, gap = GAP)) + } + + @Test + fun `body taller than the pane is centred instead of clamped to an empty range`() { + val pane = Rectangle(0, 0, 2000, 400) + + assertEquals(200, HeaderPopupGeometry.centerY(pane, y = 10, height = 900, gap = GAP)) + } + + private fun beside(chat: Rectangle) = HeaderPopupGeometry.beside( + pane = Rectangle(0, 0, 2000, 1000), + chat = chat, + fit = fit(), + ) + + private fun fit() = HeaderPopupFit( + chromeWidth = CHROME, + chromeHeight = CHROME_HEIGHT, + gap = GAP, + maxWidth = CAP, + maxHeight = CAP_HEIGHT, + ) +} From 10d0a21196be264cda03845a0b1bd776c7461565 Mon Sep 17 00:00:00 2001 From: kirillk Date: Mon, 24 Aug 2026 15:56:39 -0400 Subject: [PATCH 30/30] refactor(jetbrains): rename worktree metadata file to jetbrains.json --- .../backend/rpc/KiloWorktreeRpcApiImpl.kt | 2 +- .../backend/rpc/KiloWorktreeRpcApiImplTest.kt | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt index dc033a032b64..44bd19f386fa 100644 --- a/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt @@ -610,7 +610,7 @@ internal fun parsePrHeadRef(raw: String): String { private val json = Json { prettyPrint = true; ignoreUnknownKeys = true } private val codec = MapSerializer(String.serializer(), String.serializer()) -private const val WORKTREE_NAMES_FILE = "worktree-names.json" +private const val WORKTREE_NAMES_FILE = "jetbrains.json" @Serializable private data class WorktreeNamesFile( diff --git a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt index 28616656d018..e19a9a386b11 100644 --- a/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt +++ b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImplTest.kt @@ -146,7 +146,7 @@ class KiloWorktreeRpcApiImplTest { @Test fun `worktree names store round trips and tolerates missing or corrupt files`() { - val file = repo.resolve(".kilo").resolve("worktree-names.json") + val file = repo.resolve(".kilo").resolve("jetbrains.json") assertTrue(readWorktreeNames(file).isEmpty()) writeWorktreeNames(file, mapOf("/repo/.kilo/worktrees/feature-x" to "Feature Label", "/blank" to "")) @@ -160,7 +160,7 @@ class KiloWorktreeRpcApiImplTest { @Test fun `worktree state round trips and migrates legacy names`() { - val file = repo.resolve(".kilo").resolve("worktree-names.json") + val file = repo.resolve(".kilo").resolve("jetbrains.json") val first = "/repo/.kilo/worktrees/zebra" val second = "/repo/.kilo/worktrees/alpha" @@ -241,7 +241,7 @@ class KiloWorktreeRpcApiImplTest { val listed = api.list(repo.toString()).worktrees.filter { !it.main } assertEquals(listOf(first.path, second.path), listed.map { it.path }) - assertEquals(listOf(first.path, second.path), readWorktreeState(repo.resolve(".kilo").resolve("worktree-names.json")).worktreeOrder) + assertEquals(listOf(first.path, second.path), readWorktreeState(repo.resolve(".kilo").resolve("jetbrains.json")).worktreeOrder) } @Test @@ -256,7 +256,7 @@ class KiloWorktreeRpcApiImplTest { assertEquals(listOf(second.path, first.path), listed.map { it.path }) assertEquals( listOf(second.path, first.path), - readWorktreeState(repo.resolve(".kilo").resolve("worktree-names.json")).worktreeOrder, + readWorktreeState(repo.resolve(".kilo").resolve("jetbrains.json")).worktreeOrder, ) } @@ -268,7 +268,7 @@ class KiloWorktreeRpcApiImplTest { assertTrue(api.reorder(repo.toString(), listOf("/does/not/exist", second.path))) - val order = readWorktreeState(repo.resolve(".kilo").resolve("worktree-names.json")).worktreeOrder + val order = readWorktreeState(repo.resolve(".kilo").resolve("jetbrains.json")).worktreeOrder assertEquals(listOf(second.path, first.path), order) } @@ -288,7 +288,7 @@ class KiloWorktreeRpcApiImplTest { val removed = api.remove(repo.toString(), first.path, first.branch) assertTrue(removed.ok, "remove should report success: ${removed.error}") - val state = readWorktreeState(repo.resolve(".kilo").resolve("worktree-names.json")) + val state = readWorktreeState(repo.resolve(".kilo").resolve("jetbrains.json")) assertEquals(mapOf(second.path to "Second"), state.names) assertEquals(listOf(second.path), state.worktreeOrder) } @@ -304,7 +304,7 @@ class KiloWorktreeRpcApiImplTest { assertEquals("Feature Label", assertNotNull(renamed.worktree).name) val listed = api.list(repo.toString()).worktrees.single { it.path == created.path } assertEquals("Feature Label", listed.name) - assertEquals(mapOf(created.path to "Feature Label"), readWorktreeNames(repo.resolve(".kilo").resolve("worktree-names.json"))) + assertEquals(mapOf(created.path to "Feature Label"), readWorktreeNames(repo.resolve(".kilo").resolve("jetbrains.json"))) } @Test @@ -318,7 +318,7 @@ class KiloWorktreeRpcApiImplTest { assertEquals("Fix login bug", assertNotNull(adopted.worktree).name) val listed = api.list(repo.toString()).worktrees.single { it.path == created.path } assertEquals("Fix login bug", listed.name) - assertEquals(mapOf(created.path to "Fix login bug"), readWorktreeNames(repo.resolve(".kilo").resolve("worktree-names.json"))) + assertEquals(mapOf(created.path to "Fix login bug"), readWorktreeNames(repo.resolve(".kilo").resolve("jetbrains.json"))) } @Test