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/.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/.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/.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/.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/.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/.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-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/.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/.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/.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-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/.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/.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/.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/.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/.changeset/wet-lemons-walk.md b/.changeset/wet-lemons-walk.md new file mode 100644 index 000000000000..7ca02de73577 --- /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. 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/.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/.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/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/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/app/KiloBackendSessionManager.kt index 8cfe58b3f37a..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), @@ -163,6 +205,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/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/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/KiloWorktreeRpcApiImpl.kt index 07a12ddc98c7..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 @@ -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,15 +25,19 @@ 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 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 +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 +71,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 +187,95 @@ 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 + } + + /** + * Every failure path — including a throw from capture, worktree creation bookkeeping, or the + * 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 { + 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 + // 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 = 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(captured, base, target) } + if (!applied.ok) { + leftover = null + rollback(directory, worktree, branch, "transfer failure") + emit(MoveProgressDto(MoveStage.ERROR, error = applied.error ?: "Failed to apply changes to worktree")) + return@flow + } + // 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)) + } 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") + 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() @@ -328,6 +426,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 } @@ -495,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/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..d7b2fa39c32e --- /dev/null +++ b/packages/kilo-jetbrains/backend/src/main/kotlin/ai/kilocode/backend/rpc/WorktreeTransfer.kt @@ -0,0 +1,180 @@ +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 java.util.concurrent.TimeUnit +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 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) + 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 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) + } catch (e: Exception) { + temps.forEach { Files.deleteIfExists(it) } + throw e + } + } + + /** + * 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 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") + 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() + // 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() + 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) { + Files.deleteIfExists(file) + LOG.warn("worktree move: $label failed: ${e.message}", e) + throw e + } + } + + /** 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/KiloBackendActivityManagerTest.kt b/packages/kilo-jetbrains/backend/src/test/kotlin/ai/kilocode/backend/app/KiloBackendActivityManagerTest.kt index 32616590907a..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 { @@ -89,6 +96,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/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..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 = """[ @@ -309,6 +349,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 @@ -387,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/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..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 @@ -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 @@ -143,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 "")) @@ -157,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" @@ -238,7 +241,40 @@ 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 + 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("jetbrains.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("jetbrains.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 @@ -252,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) } @@ -268,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 @@ -282,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 @@ -320,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 @@ -376,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 @@ -409,6 +445,138 @@ 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) + } + + @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") + } + + @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 + } + 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 9897495b1b8d..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 @@ -12,9 +12,10 @@ 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.icons.AllIcons import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DataProvider @@ -24,19 +25,19 @@ 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 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 -import java.awt.ComponentOrientation import javax.swing.JPanel /** @@ -98,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) @@ -122,6 +124,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,10 +135,22 @@ 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 } + 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 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")) + agentManagerPanel.configure(anchor = chat, onCreate = { agents() }) + } + manager.onMoveToWorktree = { id, dir -> + agents() + agentManagerPanel.move(id, dir) + } val listener = object : ContentManagerListener { override fun selectionChanged(event: ContentManagerEvent) { if (event.operation == ContentManagerEvent.ContentOperation.add && event.content === agentContent) { @@ -148,6 +163,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"), @@ -165,13 +190,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/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..e1b17be04409 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/actions/ChatMoveToWorktreeAction.kt @@ -0,0 +1,48 @@ +package ai.kilocode.client.actions + +import ai.kilocode.client.plugin.KiloBundle +import ai.kilocode.client.session.ui.header.ChatDockKeys +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 + +/** + * "Move to Worktree" action shown in the chat branch dock. Visible only when there is something to + * 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 + + 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 + } + e.presentation.isEnabledAndVisible = dock.moveEnabled() + e.presentation.icon = BRANCH + e.presentation.text = KiloBundle.message("session.dock.move") + e.presentation.description = moveTooltip(dock.changeCount(), dock.hasSession()) + } + + override fun actionPerformed(e: AnActionEvent) { + e.getData(ChatDockKeys.DOCK)?.triggerMove() + } + + 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 { + 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/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/AgentManagerPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/AgentManagerPanel.kt index 7bada546ebf9..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 @@ -13,12 +14,11 @@ 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.prTooltip +import ai.kilocode.client.agentManager.worktree.openWorktreeSession 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.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 @@ -32,6 +32,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 @@ -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() @@ -91,12 +103,14 @@ 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) } }), + reorder = ActiveListReorder( + movable = { row -> row is WorktreeRow && !row.current && row.progress == null }, + onMove = { move -> controller.reorder(move.keys) }, + ), ) - private var selected: String? = null private var stats: Map = emptyMap() private var prs: Map = emptyMap() @@ -112,9 +126,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() @@ -146,28 +161,28 @@ class AgentManagerPanel( } fun refresh() { - selected = currentEditorWorktree() + if (list.selectedKeys().isEmpty()) currentEditorWorktree()?.let { list.select(it, scroll = false) } controller.reload() project?.service()?.refreshStats() 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) + private fun remove(item: WorktreeDto, force: Boolean) { controller.remove(item, force, onFailure = { result -> notifyFailed(item, result, force) }) } @@ -202,9 +217,8 @@ class AgentManagerPanel( private fun open(item: WorktreeDto, focus: Boolean) { val target = project ?: return - if (item.main || controller.isPending(item.id)) return - ensureWorktreeSessionEditorKind() - target.service().open(WorktreeSessionEditorKind.ID, worktreeSessionParams(item), focus) + if (controller.progress(item.id) != null) return + openWorktreeSession(target, item, focus) } private fun close(item: WorktreeDto) { @@ -223,13 +237,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) { @@ -252,8 +266,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 { @@ -263,7 +276,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 } /** @@ -272,9 +285,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)) @@ -288,7 +299,6 @@ class AgentManagerPanel( * the selection somewhere unpredictable. */ private fun advance(next: WorktreeDto?) { - selected = next?.id if (next == null) { list.clearSelection() return @@ -311,6 +321,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) @@ -349,37 +363,44 @@ class AgentManagerPanel( } private fun sync() { - val key = selected + val current = controller.current?.let { item -> + WorktreeRow( + item, + progress = null, + 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.progress(item.id), + controller.kind(item.path), + stats[key], + pull, + ) }, - ActiveListSelection.PreserveNoScroll, + ActiveListSelection.Preserve, ) - 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() } @@ -409,6 +430,7 @@ class AgentManagerPanel( override fun dispose() { controller.onSelect = null controller.onCreateFailure = null + controller.onMoveFailure = null controller.onRemoveSuccess = null controller.onActivityChanged = null } @@ -460,27 +482,24 @@ 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?, + 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 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 - override val icon = WorktreeIcons.forRow(dto.locked, pending) + 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 badges: List - get() { - if (pending || deleting) return emptyList() - return listOfNotNull(kind?.let(::worktreeActivityBadge)) - } 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 @@ -499,20 +518,20 @@ 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 + pr == row.pr && + current == row.current } 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) + result = 31 * result + current.hashCode() return result } } @@ -528,4 +547,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/KiloWorktreeService.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/KiloWorktreeService.kt index c5ccf4f2a227..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 @@ -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,21 @@ class KiloWorktreeService internal constructor( WorktreePrListDto() } + /** + * 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 + * 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) } @@ -127,4 +145,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/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/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/WorktreeActivity.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivity.kt index 0e561668a34f..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('/') @@ -24,12 +19,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/WorktreeController.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeController.kt index f50e94d08c68..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 @@ -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,16 @@ 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() 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 @@ -62,13 +66,18 @@ 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() fun isPending(id: String): Boolean = id in pending - fun isDeleting(id: String): Boolean = id in deleting + fun progress(id: String): String? = tasks[id] fun kind(path: String): SessionActivityKind? = kinds[normalizeWorktreePath(path)] @@ -81,6 +90,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" @@ -110,6 +120,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) } @@ -124,6 +135,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) } @@ -142,6 +154,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) @@ -168,13 +181,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) @@ -187,7 +201,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", @@ -199,6 +213,56 @@ 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) { + 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 + tasks[temp.id] = label(MoveStage.CAPTURING) + model.add(temp) + onSelect?.invoke(temp.id) + cs.launch { + var stage = MoveStage.CAPTURING + runCatching { + if (sessionId != null) 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(key) + 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) + // 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", "session" to (sessionId != null).toString()), + ) + } + MoveStage.ERROR -> failMove(key, temp, event.error, stage) + else -> Unit + } + } + } + }.onFailure { err -> edt { failMove(key, temp, err.message, stage) } } + } + } + fun rename( dto: WorktreeDto, name: String, @@ -234,6 +298,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 @@ -256,6 +339,24 @@ class WorktreeController( return (0 until model.size).firstOrNull { model.getElementAt(it).id == id } ?: -1 } + 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) + 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 586097001fbb..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 @@ -1,5 +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 @@ -7,11 +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 - fun forRow(locked: Boolean, pending: Boolean): Icon = when { - pending -> spinner - locked -> this.locked - else -> branch + // 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 + + /** + * 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. 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( + busy: Boolean, + kind: SessionActivityKind? = null, + locked: Boolean = false, + current: Boolean = false, + ): Icon { + if (busy) 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/agentManager/worktree/WorktreePrHeaderView.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderView.kt index 90a2ea0f2eaf..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 @@ -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 = 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(prefix: String, next: String?, nextTip: String?) { - val full = listOfNotNull(prefix, next).joinToString(" ") - var changed = false - if (text != full) { - text = full - title.clear() - if (next == null) { - title.append(prefix, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) - } else { - title.append("$prefix ", SimpleTextAttributes.GRAYED_ATTRIBUTES) - title.append(next, SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getLabelForeground())) - } - 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..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 @@ -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 @@ -38,11 +39,14 @@ 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() + // 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() } 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) } @@ -57,6 +61,10 @@ internal fun unregisterWorktreeSessionEditorKind() { service().unregister(WorktreeSessionEditorKind.ID) } -internal fun worktreeSessionParams(item: WorktreeDto): Map = linkedMapOf( - "path" to item.path, -) +/** 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, focus: Boolean = true) { + ensureWorktreeSessionEditorKind() + project.service().open(WorktreeSessionEditorKind.ID, worktreeSessionParams(worktree), focus) +} 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/WorktreeSessionEditorPanel.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeSessionEditorPanel.kt index 3fd5747820ad..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 @@ -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 @@ -561,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, @@ -576,7 +572,9 @@ class WorktreeSessionEditorPanel( return name } override val tooltip: String get() = title - override val badges: List get() = listOfNotNull(kind?.let(::worktreeActivityBadge)) + override val progress: String? get() = if (deleting) KiloBundle.message("common.deleting") else null + override val badges: List + 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/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/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/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/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/session/SessionManager.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SessionManager.kt index 32e788ce4353..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 @@ -15,6 +15,18 @@ 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() {} + + /** 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) @@ -27,7 +39,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..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 @@ -49,6 +49,24 @@ 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 + + /** 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 615548976bc5..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 @@ -43,6 +43,8 @@ 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.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 +52,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 +196,10 @@ class SessionUi( private lateinit var header: SessionHeaderPanel + private var dock: BranchDock? = null + + private var bottom: JComponent? = null + internal lateinit var scroll: SessionScroll private lateinit var question: QuestionView @@ -224,6 +231,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 +244,11 @@ class SessionUi( bindStyle() bindMigration() onStateChanged(controller.model.state) - if (showBranchBadge()) refreshBranchChanges() + dock?.let { + syncDock() + refreshBranchChanges() + refreshBranch() + } loaded?.let(::finishOpen) } @@ -411,7 +423,13 @@ 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 + val move = if (owner?.supportsMoveToWorktree == true) ::moveToWorktree else null + dock = BranchDock(openDiff = ::openBranchChanges, onMove = move, onNewWorktree = newWorktree) + } scroll = SessionScroll(root, sessionContent, messageBody, blankBody) overlay = SessionHoverCopyOverlay(root, scroll.component, this) @@ -457,12 +475,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 +506,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 +641,36 @@ class SessionUi( is SessionModelEvent.RevertChanged -> onRevertChanged(event.revert) + is SessionModelEvent.MessageAdded, + is SessionModelEvent.MessageRemoved, + is SessionModelEvent.HistoryLoaded, + is SessionModelEvent.Cleared -> syncDock() + 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 syncDock() { + val dock = dock ?: return + dock.setHasMessages(controller.model.messages().isNotEmpty()) + dock.setHasSession(controller.id != null) + } + @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,18 @@ 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 through the side-panel manager. */ + @RequiresEdt + private fun moveToWorktree() { + manager?.moveToWorktree(controller.id, controller.sessionDirectory) + } + @RequiresEdt private fun openBranchDiff(branch: String?) { // No store seeding: the diff editor's fetch recomputes branchDiff authoritatively, so a @@ -971,7 +1011,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 +1095,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) { @@ -1041,6 +1106,7 @@ class SessionUi( pendingRedo = null } prompt.setBusy(busy) + dock?.setBusy(busy) load.setState(state) scroll.setQuestionPending(questionPending(state)) scroll.show(body(state)) @@ -1049,6 +1115,7 @@ class SessionUi( } private fun onSessionUpdated() { + syncDock() manager?.activityChanged() } @@ -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/SpinnerIcon.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt new file mode 100644 index 000000000000..ffb5d0e0de83 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/SpinnerIcon.kt @@ -0,0 +1,96 @@ +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. 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`). + */ +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 = color() + 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() + } + } + } + + fun color() = UiStyle.Colors.running() +} 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/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..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,31 +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) { - 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() + localList.update(localRows, ActiveListSelection.Slide) + cloudList.update(cloudRows, ActiveListSelection.Slide) } @RequiresEdt @@ -477,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/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/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/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/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/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) 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..22ebc4080ca2 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/BranchDock.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.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 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.ui.SimpleTextAttributes +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. 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. + */ +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(titleStyle = titleStyle, openDiff = 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 hasSession = false + private var busy = false + + 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).align(HAlign.TRACK, VAlign.CENTER)) + 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(), + ) + } + + 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 setBusy(value: Boolean) { + if (busy == value) return + busy = value + sync() + } + + /** + * 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 + syncToolbar() + } + + // ---- state read by the toolbar actions ---- + + fun newWorktreeEnabled(): Boolean = onNewWorktree != null && 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 + + private fun dockActive(): Boolean = gitAvailable() && !busy && (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() + 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..eec87f1dcffe --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/session/ui/header/PrHeaderView.kt @@ -0,0 +1,198 @@ +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( + private val titleStyle: Int = SimpleTextAttributes.STYLE_BOLD, + 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 + val attrs = SimpleTextAttributes(titleStyle, UIUtil.getLabelForeground()) + if (body == null) { + title.append(number, attrs) + } else { + title.append(body, attrs) + 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 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/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/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/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/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/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/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..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 @@ -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.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/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/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/kotlin/ai/kilocode/client/ui/UiStyle.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/UiStyle.kt index a1a90e498e7d..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,8 @@ 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 import com.intellij.util.ui.JBUI @@ -38,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) @@ -48,10 +53,25 @@ 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. */ object Badge { + private const val PR_SOFT_ALPHA = 0.15 + interface Style { fun bg(): Color @@ -108,64 +128,84 @@ 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 PullRequestOpen : Style { + object ActivityAttention : Style { override fun bg(): Color = JBColor.namedColor( - "Kilo.PullRequest.openBadgeBackground", - JBColor(Color(0x1F, 0x88, 0x3D), Color(0x23, 0x86, 0x36)), + "Kilo.Activity.attentionBackground", + JBColor(Color(0xE6, 0x6D, 0x17), Color(0xC7, 0x7D, 0x55)), ) override fun fg(): Color = JBColor.namedColor( - "Kilo.PullRequest.openBadgeForeground", + "Kilo.Activity.attentionForeground", Color.WHITE, ) } - object PullRequestDraft : Style { + object ActivityError : Style { override fun bg(): Color = JBColor.namedColor( - "Kilo.PullRequest.draftBadgeBackground", - JBColor(Color(0x6E, 0x77, 0x81), Color(0x6E, 0x76, 0x81)), + "Kilo.Activity.errorBackground", + JBColor(Color(0xE5, 0x57, 0x65), Color(0xDB, 0x5C, 0x5C)), ) override fun fg(): Color = JBColor.namedColor( - "Kilo.PullRequest.draftBadgeForeground", + "Kilo.Activity.errorForeground", Color.WHITE, ) } - object PullRequestMerged : Style { - override fun bg(): Color = JBColor.namedColor( - "Kilo.PullRequest.mergedBadgeBackground", - JBColor(Color(0x82, 0x50, 0xDF), Color(0x89, 0x57, 0xE5)), + object PullRequestOpen : Style { + private val accent = JBColor.namedColor( + "Kilo.PullRequest.openBadgeForeground", + JBColor(Color(0x1A, 0x7F, 0x37), Color(0x3F, 0xB9, 0x50)), ) - override fun fg(): Color = JBColor.namedColor( - "Kilo.PullRequest.mergedBadgeForeground", - Color.WHITE, + override fun bg(): Color = ColorUtil.withAlpha(accent, PR_SOFT_ALPHA) + + override fun fg(): Color = accent + } + + object PullRequestDraft : Style { + private val accent = JBColor.namedColor( + "Kilo.PullRequest.draftBadgeForeground", + 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 PullRequestClosed : Style { - override fun bg(): Color = JBColor.namedColor( - "Kilo.PullRequest.closedBadgeBackground", - JBColor(Color(0xCF, 0x22, 0x2E), Color(0xDA, 0x36, 0x33)), + object PullRequestMerged : Style { + private val accent = JBColor.namedColor( + "Kilo.PullRequest.mergedBadgeForeground", + JBColor(Color(0x82, 0x50, 0xDF), Color(0xA3, 0x71, 0xF7)), ) - override fun fg(): Color = JBColor.namedColor( + override fun bg(): Color = ColorUtil.withAlpha(accent, PR_SOFT_ALPHA) + + override fun fg(): Color = accent + } + + object PullRequestClosed : Style { + 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 } } @@ -177,6 +217,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/ActiveList.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveList.kt index 46becf2dbc91..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 @@ -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 { @@ -94,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() @@ -128,7 +133,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 edf5d375e04c..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 @@ -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 @@ -104,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 } @@ -121,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() @@ -224,7 +230,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..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 @@ -20,10 +19,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 +131,7 @@ internal class ActiveListRenderer( ) private val wrap = PickerRow() private var bodyHeight: Int? = null + private var gap = false init { isOpaque = true @@ -183,8 +190,8 @@ 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 titleFg = if (value.deleting) weak else fg + val weak = UiStyle.Colors.weak() + val titleFg = if (value.progress != null) weak else fg val section = activeListSectionTitle(model.items, index) background = list.background @@ -199,7 +206,22 @@ 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() + // 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) @@ -216,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. @@ -245,6 +267,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,8 +314,39 @@ 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) + // 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() + } + return image to Point(wrap.x, wrap.y) + } + 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/ActiveListReorder.kt b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt new file mode 100644 index 000000000000..02cd56242d3e --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/main/kotlin/ai/kilocode/client/ui/list/ActiveListReorder.kt @@ -0,0 +1,87 @@ +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 + // 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 +} + +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..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 @@ -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,10 @@ internal class ActiveListView( private var popups = 0 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 @@ -128,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) } @@ -137,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() @@ -151,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() @@ -167,13 +174,13 @@ 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() } 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 @@ -193,13 +200,18 @@ 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() override fun focusLost(e: FocusEvent) = list.repaint() }) + reorder?.let { installActiveListReorder(this, list, it) } ScrollingUtil.installActions(list) next(list) } @@ -213,6 +225,8 @@ internal class ActiveListView( @RequiresEdt fun clearSelection() { checkEdt() + anchor = emptySet() + mark = -1 list.clearSelection() } @@ -237,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 @@ -246,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() @@ -293,20 +321,15 @@ 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, - ActiveListSelection.PreserveNoScroll, - ActiveListSelection.Preserve, - -> null + when (selection) { + is ActiveListSelection.Key -> { + anchor = setOf(selection.key) + mark = -1 + sync(Absent.KEEP) + } + ActiveListSelection.Slide -> sync(Absent.SLIDE) + ActiveListSelection.Preserve -> sync(Absent.KEEP) } - sync(key, idx, selection != ActiveListSelection.PreserveNoScroll) } @RequiresEdt @@ -336,29 +359,85 @@ 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, at: Int? = null) { checkEdt() val q = filter.trim() - val rows = if (q.isBlank()) items else items.filter { matcher(q, it) } - // 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) + 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 + // 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, 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 } - syncCellHeight(rows) + } + + /** + * 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, at: Int?) { + 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) { + list.selectedIndex = idx + mark = idx + return + } + val indices = anchor.mapNotNull { id -> activeListIdentityIndex(rows, id).takeIf { it >= 0 } } + if (indices.isNotEmpty()) { + list.selectedIndices = indices.toIntArray() + mark = indices.min() + 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) + list.selectedIndex = next + anchor = setOf(rows[next].identity) + mark = next + } + Absent.FIRST -> { + if (rows.isEmpty()) { + list.clearSelection() + return + } + list.selectedIndex = 0 + 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() @@ -422,20 +501,23 @@ 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 fun primary() { checkEdt() - val item = list.selectedValue ?: return + val item = active() ?: return primary(item) } private fun open(focus: Boolean) { - val item = list.selectedValue ?: return - if (item.deleting) return + val item = active() ?: return + if (item is ActiveListGap) return + if (item.progress != null) return val action = onOpen if (action != null) { action(item, focus) @@ -446,10 +528,18 @@ internal class ActiveListView( private fun source() { val item = list.selectedValue ?: return - if (item.deleting) return + if (item is ActiveListGap) return + if (item.progress != null) return 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. @@ -457,7 +547,8 @@ internal class ActiveListView( * action is destructive (e.g. delete) does nothing on double-click. */ private fun activate(item: ActiveListItem) { - if (item.deleting) return + if (item is ActiveListGap) return + if (item.progress != null) return val action = onActivate if (action != null) { action(item) @@ -473,7 +564,8 @@ internal class ActiveListView( } private fun primary(item: ActiveListItem) { - if (item.deleting) return + if (item is ActiveListGap) return + if (item.progress != null) return val cells = activeListVisibleCells(item, true) val cell = cells.firstOrNull { it.enabled && it.primary } if (cell != null) { @@ -507,6 +599,100 @@ 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.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 + 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 + } + // 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) + drag = state + } + val run = activeListSectionRun(base, from) + if (run.isEmpty()) return + 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) + sync(at = next) + } + + @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 + anchor = setOf(state.key) + mark = target + sync(at = target) + 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 +713,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 +726,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,7 +745,8 @@ 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.disabled || item.deleting || !cfg.available(item)) return false + if (item is ActiveListGap) 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( @@ -603,6 +792,31 @@ 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 + 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 } + } + override fun getBackground(): Color { if (surface == ActiveListSurface.ToolWindow) return activeListToolWindowBackground() return super.getBackground() ?: UIUtil.getPanelBackground() @@ -637,12 +851,16 @@ 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, val rows: List, ) + private enum class Absent { KEEP, SLIDE, FIRST } + } private data class ActiveListHeightRow( @@ -656,7 +874,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 { @@ -671,25 +889,42 @@ private fun activeListHeightRow(item: ActiveListItem): ActiveListHeightRow { item.trailing, item.cells, item.disabled, - item.deleting, + item.progress, ) } 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) } +/** + * 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 { + /** Select nothing while the remembered rows are absent, and pick them up again if they return. */ data object Preserve : ActiveListSelection - data object PreserveNoScroll : ActiveListSelection + + /** + * 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/main/resources/icons/worktree-local.svg b/packages/kilo-jetbrains/frontend/src/main/resources/icons/worktree-local.svg new file mode 100644 index 000000000000..c5481bc9297a --- /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..d40fa8f60f49 --- /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/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/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 0f0bd29d2674..aeff0f994ae1 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,14 @@ 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.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 @@ -345,6 +353,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 @@ -362,10 +371,10 @@ 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.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. @@ -404,7 +413,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/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) 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 27ab26a287d1..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,24 +3,31 @@ 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 +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 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 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 +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 @@ -119,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) } @@ -174,6 +215,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") @@ -192,7 +273,25 @@ class AgentManagerPanelTest : BasePlatformTestCase() { assertEquals(second.id, edt { (list.selectedValue as ActiveListItem).key }) } - fun `test refresh selects active worktree editor`() { + 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") rpc.listed += first @@ -210,6 +309,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 }) } @@ -396,7 +515,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 +527,45 @@ class AgentManagerPanelTest : BasePlatformTestCase() { flush() val row = row(panel, 0) - assertEquals(listOf(ActiveListBadge(SessionActivityKind.QUESTION.label(), SessionActivityKind.QUESTION.style())), row.badges) + assertSame(SessionActivityKind.QUESTION.icon(), row.icon) + assertEquals(emptyList(), row.badges) + } + + 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), + )) + rpc.listed += item + val controller = WorktreeController(service, "/test", coroutines.scope, activity = activity) + val panel = edt { AgentManagerPanel(testRootDisposable, controller) } + edt { controller.reload() } + flush() + + 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`() { @@ -514,7 +671,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), @@ -528,11 +685,158 @@ class AgentManagerPanelTest : BasePlatformTestCase() { flush() 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() } + 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 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") + 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) @@ -550,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 3695c5dfb29c..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 @@ -5,13 +5,17 @@ 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 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 @@ -19,7 +23,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 @@ -56,6 +62,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`() { @@ -158,13 +165,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) } @@ -183,7 +190,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) } @@ -318,6 +325,125 @@ 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)) + // 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" && 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`() { + 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() @@ -348,27 +474,61 @@ class WorktreeControllerTest : BasePlatformTestCase() { } } - fun `test worktree icons prefer pending then locked then branch`() { - assertSame(WorktreeIcons.spinner, WorktreeIcons.forRow(locked = false, pending = true)) - assertSame(WorktreeIcons.locked, WorktreeIcons.forRow(locked = true, pending = false)) - assertSame(WorktreeIcons.branch, WorktreeIcons.forRow(locked = false, pending = false)) + fun `test worktree row icons show only while running or waiting`() { + assertSame( + WorktreeIcons.spinner, + WorktreeIcons.forRow(busy = true, kind = SessionActivityKind.RUNNING), + ) + assertSame( + WorktreeIcons.running, + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.RUNNING), + ) + assertSame( + SessionActivityKind.QUESTION.icon(), + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.QUESTION), + ) + assertSame( + SessionActivityKind.PLAN.icon(), + WorktreeIcons.forRow(busy = false, kind = SessionActivityKind.PLAN), + ) + 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`() { + // 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) + 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) + } + } finally { + if (GraphicsEnvironment.isHeadless()) IconLoader.deactivate() + } } - fun `test branch and lock 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) + 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`() { 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`() { @@ -431,8 +591,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 new file mode 100644 index 000000000000..72a98c1dde63 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/WorktreeIconsTest.kt @@ -0,0 +1,93 @@ +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`() { + assertSame(WorktreeIcons.running, WorktreeIcons.forRow(busy = 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 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 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(busy = false, kind = SessionActivityKind.QUESTION), + ) + 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(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(busy = false, kind = SessionActivityKind.ERROR)) + assertSame( + WorktreeIcons.local, + 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(busy = false, kind = SessionActivityKind.RUNNING, current = true), + ) + } +} 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/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/agentManager/worktree/WorktreeActivityTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreeActivityTest.kt index d5b365b95518..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 @@ -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( @@ -40,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/WorktreePrHeaderViewTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/agentManager/worktree/WorktreePrHeaderViewTest.kt index e738c1fa7fb2..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 @@ -34,9 +36,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")) 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..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 @@ -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 session rows match history visuals`() { + 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 @@ -248,11 +248,23 @@ class WorktreeSessionEditorPanelTest : BasePlatformTestCase() { assertEquals("Session ses_1", row.title) assertNull(row.icon) assertNull(row.description) - assertEquals(listOf(ActiveListBadge(SessionActivityKind.RUNNING.label(), SessionActivityKind.RUNNING.style())), 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() } @@ -277,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/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/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 55f07883155e..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 @@ -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 @@ -19,12 +20,16 @@ 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 +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 @@ -34,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 @@ -82,13 +89,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 +168,111 @@ class SessionUiLayoutTest : SessionUiTestBase() { assertNull(drop.dropTarget) } - fun `test branch changes badge refreshes on finish and revert`() { + 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 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 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) + } + ApplicationManager.getApplication() + .replaceService(KiloWorktreeService::class.java, KiloWorktreeService(scope, worktree), testRootDisposable) + workspaceRpc.branchDiffs.add(DiffFileDto("src/A.kt", 2, 1)) + // 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) + assertTrue(dock.moveEnabled()) + + dock.triggerMove() + + assertEquals(listOf>(null to "/test"), calls) + } + + 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)) - 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 +280,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 +415,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 +432,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 +454,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) } @@ -327,15 +467,16 @@ 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(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()) } @@ -348,15 +489,16 @@ 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(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 +968,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/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/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/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/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") + } } 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..517ffc7d1823 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/BranchDockTest.kt @@ -0,0 +1,331 @@ +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 +import ai.kilocode.rpc.dto.GhAvailability +import ai.kilocode.rpc.dto.GhState +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 +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() { + + // ---- 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 }) + } + + 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`() { + 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) + } + + // ---- 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) + dock.setHasSession(true) + } + val p = update(ChatMoveToWorktreeAction(), dock) + 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`() { + 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.setHasSession(true) + } + val p = update(ChatMoveToWorktreeAction(), dock) + assertTrue(p.isVisible) + assertEquals(KiloBundle.message("session.dock.move.tooltip.one"), p.description) + } + + 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), DiffFileDto("src/B.kt", 1, 0))) + } + // 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`() { + 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 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) + } + + 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`() { + 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 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) } + 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..8c39ba9bdc7e --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/session/ui/header/PrHeaderViewTest.kt @@ -0,0 +1,143 @@ +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.SimpleTextAttributes +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 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 {} } + + 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 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) { + 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/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, + ) +} 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) } 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/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 } 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..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 @@ -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 bold`() { + 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) + + // 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_BOLD, iter.textAttributes.style) + assertEquals("Alpha", iter.fragment) + } + } + fun `test narrow row squeezes title but keeps tags full width`() { edt { val row = object : ActiveListItem { @@ -445,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") @@ -744,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) } } @@ -767,7 +800,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 +818,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 +839,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/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/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..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 @@ -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,12 +27,20 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { var statsResult = WorktreeStatsListDto() 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. */ + var moveScript: List = emptyList() val creates = CopyOnWriteArrayList() val removes = CopyOnWriteArrayList>() 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 = {} @@ -83,6 +95,18 @@ class FakeWorktreeRpcApi : KiloWorktreeRpcApi { return prResult } + override suspend fun branchStatus(directory: String): BranchStatusDto { + assertNotEdt("branchStatus") + branchThrows?.let { throw it } + 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) @@ -123,4 +147,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/UiStyleTest.kt b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/UiStyleTest.kt index e2710a9867aa..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 @@ -50,11 +49,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`() { @@ -63,4 +63,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) + } + } } 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..b52a388b2d14 --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListReorderTest.kt @@ -0,0 +1,319 @@ +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() { + + 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 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) + 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 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()) + 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) + } + + 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)) + } + + 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, + ): ActiveListView { + return ActiveListView( + empty = "", + cfg = cfg, + 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) } + } + + /** 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 } + } + + 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?, identity: Any = key): ActiveListItem = object : ActiveListItem { + override val key = key + override val identity = identity + override val title = key + override val section = section + } +} 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..c8e9b02ac14c --- /dev/null +++ b/packages/kilo-jetbrains/frontend/src/test/kotlin/ai/kilocode/client/ui/list/ActiveListSelectionTest.kt @@ -0,0 +1,247 @@ +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() { + + 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 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")) + + assertFalse(view.select("b")) + assertNull(view.selected()) + view.update(rows("a", "b")) + + 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"))) + 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) + } + + 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 } + } + + 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 + } +} 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/KiloWorktreeRpcApi.kt b/packages/kilo-jetbrains/shared/src/main/kotlin/ai/kilocode/rpc/KiloWorktreeRpcApi.kt index 63b7b09ef794..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 @@ -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,21 @@ 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. 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 listBranches(directory: String): WorktreeBranchesDto suspend fun create(directory: String, request: CreateWorktreeRequestDto): CreateWorktreeResultDto @@ -61,4 +79,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 } 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..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 @@ -53,6 +53,7 @@ enum class SessionActivityKindDto { QUESTION, PLAN, PERMISSION, + ERROR, } @Serializable @@ -66,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, +) 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..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 @@ -50,6 +50,31 @@ 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 error: String? = null, + val worktree: WorktreeDto? = null, + val session: String? = null, +) + @Serializable data class WorktreeBranchesDto( val branches: List = emptyList(),