Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/orphan-worktree-cleanup-ui.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Move the Agent Manager leftover worktree folder notice to the top of the worktree list and rework its cleanup dialog to match VS Code, including an explanation of what the listed folders are before any bulk delete
6 changes: 6 additions & 0 deletions .changeset/worktree-orphan-cleanup-dialog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"kilo-code": minor
"@kilocode/kilo-jetbrains": minor
---

Leftover worktree folders now show a count and total size in the warning banner, with a "Resolve…" action that opens a dialog listing each folder's path, size, and whether it still holds a git checkout. While the total is still being measured the banner says so, and if the measurement fails it reports the count alone instead of claiming 0 B. Measuring stops as soon as you start a delete, or whenever the folder list changes, rather than walking folders that are on their way out, and then re-measures whatever is left. The dialog's explanation starts collapsed to its first paragraph behind a "Show more" link, and its checkboxes are drawn the way each IDE draws its own. Deletion runs in the background so the UI never freezes, folders that still contain a checkout are unchecked by default, and a completion notification reports how many were removed. Worktree deletion is also more thorough: JetBrains now tears down backend state and removes the snapshot repository for a deleted worktree the same way VS Code already does, and a directory that reappears immediately after deletion is cleaned up once more automatically.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,18 @@ class WorktreeTrash(private val cs: CoroutineScope) {
}
}

/** Deletes [temp] recursively on this service's own scope. Never throws into the caller. */
fun reap(temp: Path) {
track(cs.launch(Dispatchers.IO) { reapNow(temp) })
/**
* Deletes [temp] recursively on this service's own scope. Never throws into the caller.
*
* [onDone] runs after the reap attempt finishes (success or failure), still on this service's
* own IO dispatcher — callers use it for the post-reap reappearance guard: staging a worktree
* created a fresh sibling that vanished the moment the rename completed, but something can still
* recreate the original path while the recursive delete of its sibling is still in flight (a
* dev-run backend re-materializing `.kilo-dev`, for example), and only checking after the delete
* settles observes that reliably.
*/
fun reap(temp: Path, onDone: () -> Unit = {}) {
track(cs.launch(Dispatchers.IO) { reapNow(temp); onDone() })
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import ai.kilocode.rpc.dto.GhMerge
import ai.kilocode.rpc.dto.GhReview
import ai.kilocode.rpc.dto.GhState
import ai.kilocode.rpc.dto.MoveStage
import ai.kilocode.rpc.dto.OrphanKind
import ai.kilocode.rpc.dto.OrphanRemoveResultDto
import ai.kilocode.rpc.dto.WorktreeDirtyDto
import ai.kilocode.rpc.dto.WorktreeDto
import kotlinx.serialization.json.Json
Expand All @@ -30,11 +32,14 @@ import com.intellij.openapi.util.SystemInfo
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import org.junit.jupiter.api.Assumptions.assumeFalse
import org.junit.jupiter.api.Assumptions.assumeTrue
import java.nio.file.Files
Expand Down Expand Up @@ -136,12 +141,164 @@ class KiloWorktreeRpcApiImplTest {

// Orphan paths are resolved the way git reports worktree paths (realpath), so they compare
// equal to the other DTOs' paths on a symlinked temp dir.
assertEquals(listOf(leftover.toRealPath().toString()), listed.orphans)
assertEquals(listOf(leftover.toRealPath().toString()), listed.orphans.map { it.path })
assertEquals(listOf(OrphanKind.LEFTOVER), listed.orphans.map { it.kind }, "a plain directory is a leftover, not a broken checkout")
assertTrue(listed.worktrees.any { it.path == created.path }, "a live worktree is not an orphan")
// Reported, never deleted: a leftover directory can hold files that exist nowhere else.
assertTrue(Files.isDirectory(leftover.resolve(".kilo-dev")))
}

@Test
fun `list classifies an orphan that still holds a git checkout as broken`() = runBlocking {
initRepo()
val broken = repo.resolve(".kilo").resolve("worktrees").resolve("broken")
Files.createDirectories(broken)
// A plain file named `.git` is what a linked worktree checkout actually has (it points back
// at the shared `.git` dir) — a directory named `.git` is the primary repo's own shape. Either
// is enough to call the leftover "still holds a checkout".
Files.writeString(broken.resolve(".git"), "gitdir: /nowhere\n")

val listed = api.list(repo.toString())

assertEquals(listOf(broken.toRealPath().toString()), listed.orphans.map { it.path })
assertEquals(listOf(OrphanKind.BROKEN), listed.orphans.map { it.kind })
}

@Test
fun `orphanSizes sums regular file sizes and never follows symlinks`() = runBlocking {
initRepo()
val orphan = repo.resolve(".kilo").resolve("worktrees").resolve("leftover")
Files.createDirectories(orphan)
Files.write(orphan.resolve("a.bin"), ByteArray(10))
Files.write(orphan.resolve("b.bin"), ByteArray(20))
val target = Files.createTempDirectory("kilo-orphan-symlink-target")
Files.write(target.resolve("outside.bin"), ByteArray(1_000))
runCatching { Files.createSymbolicLink(orphan.resolve("link"), target) }
try {
val sizes = api.orphanSizes(repo.toString(), listOf(orphan.toString()))
assertEquals(30L, sizes[orphan.toString()], "size must exclude the symlinked tree entirely")
} finally {
delete(target)
}
}

@Test
fun `orphanSizes omits a path that fails to walk instead of failing the batch`() = runBlocking {
initRepo()
val ok = repo.resolve(".kilo").resolve("worktrees").resolve("leftover")
Files.createDirectories(ok)
Files.write(ok.resolve("a.bin"), ByteArray(5))
val missing = repo.resolve(".kilo").resolve("worktrees").resolve("does-not-exist")

val sizes = api.orphanSizes(repo.toString(), listOf(ok.toString(), missing.toString()))

assertEquals(5L, sizes[ok.toString()])
assertFalse(sizes.containsKey(missing.toString()), "a path that could not be measured must be omitted, not zero")
}

/**
* The frontend cancels a size pass whenever the orphan set changes or a delete starts, and
* `Files.walkFileTree` cannot be interrupted — so the walk has to check cancellation itself rather
* than leave a cancelled coroutine walking every remaining path on Dispatchers.IO.
*/
@Test
fun `orphanSizes stops measuring once its caller is cancelled`() = runBlocking {
initRepo()
val first = repo.resolve(".kilo").resolve("worktrees").resolve("first")
val second = repo.resolve(".kilo").resolve("worktrees").resolve("second")
Files.createDirectories(first)
Files.createDirectories(second)
Files.write(first.resolve("a.bin"), ByteArray(10))
Files.write(second.resolve("b.bin"), ByteArray(20))

val job = Job()
job.cancel()
val outcome = runCatching<Map<String, Long>> {
withContext(job) { api.orphanSizes(repo.toString(), listOf(first.toString(), second.toString())) }
Comment thread
kirillk marked this conversation as resolved.
Resolved
}

assertTrue(
outcome.exceptionOrNull() is CancellationException,
"a cancelled pass must not answer with sizes -> ${outcome.getOrNull()}",
)
}

@Test
fun `removeOrphans deletes a validated leftover directory`() = runBlocking {
initRepo()
val orphan = repo.resolve(".kilo").resolve("worktrees").resolve("leftover")
Files.createDirectories(orphan.resolve("nested"))
Files.writeString(orphan.resolve("nested").resolve("file.txt"), "hi")
val real = orphan.toRealPath().toString()

val result = api.removeOrphans(repo.toString(), listOf(real))

assertEquals(listOf(OrphanRemoveResultDto(real, ok = true)), result.results)
assertFalse(Files.exists(orphan), "the trash-unavailable fallback must delete synchronously, not defer")
assertTrue(api.list(repo.toString()).orphans.isEmpty())
}

@Test
fun `removeOrphans refuses a path outside managed storage`() = runBlocking {
initRepo()
val outside = repo.resolve("outside")
Files.createDirectories(outside)

val result = api.removeOrphans(repo.toString(), listOf(outside.toString()))

val entry = result.results.single()
assertFalse(entry.ok)
assertTrue(entry.error?.contains("Refusing") == true, entry.error)
assertTrue(Files.isDirectory(outside), "unmanaged directory must not be touched")
}

@Test
fun `removeOrphans refuses a path that is actually a registered worktree`() = runBlocking {
initRepo()
val created = assertNotNull(api.create(repo.toString(), CreateWorktreeRequestDto("feature/x")).worktree)

val result = api.removeOrphans(repo.toString(), listOf(created.path))

val entry = result.results.single()
assertFalse(entry.ok)
assertTrue(entry.error?.contains("managed worktree") == true, entry.error)
assertTrue(Files.isDirectory(Path.of(created.path)), "a live managed worktree must not be touched")
}

@Test
fun `removeOrphans rejects a stale selection that is no longer an orphan`() = runBlocking {
initRepo()
val orphan = repo.resolve(".kilo").resolve("worktrees").resolve("leftover")
Files.createDirectories(orphan)
val real = orphan.toRealPath().toString()
// Someone else already cleaned it up between the dialog's scan and this call.
delete(orphan)

val result = api.removeOrphans(repo.toString(), listOf(real))

val entry = result.results.single()
assertFalse(entry.ok)
assertTrue(entry.error?.contains("No longer an orphan") == true, entry.error)
}

@Test
fun `removeOrphans reports independent results per path`() = runBlocking {
initRepo()
val ok = repo.resolve(".kilo").resolve("worktrees").resolve("leftover")
Files.createDirectories(ok)
val okReal = ok.toRealPath().toString()
val outside = repo.resolve("outside")
Files.createDirectories(outside)

val result = api.removeOrphans(repo.toString(), listOf(okReal, outside.toString()))

assertEquals(2, result.results.size)
assertTrue(result.results.first { it.path == okReal }.ok)
assertFalse(result.results.first { it.path == outside.toString() }.ok)
assertFalse(Files.exists(ok))
assertTrue(Files.isDirectory(outside))
}

@Test
fun `list and the polls agree on which worktrees exist`() = runBlocking {
initRepo()
Expand Down Expand Up @@ -417,6 +574,53 @@ class KiloWorktreeRpcApiImplTest {
assertFalse(listed.contains(created.path), "a poll with a free lock should prune: $listed")
}

@Test
fun `checkReappearance re-stages and reaps once when the original path came back`() = runBlocking {
val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
val trash = WorktreeTrash(scope)
val trashApi = KiloWorktreeRpcApiImpl(trash)
try {
val dir = repo.resolve("reappeared")
Files.createDirectories(dir)
// Simulate a reap that already settled (the sibling from the original stage is long gone)
// while something recreated the original path afterward — the exact race the guard exists
// to catch, made deterministic instead of racing a real background reap.
val temp = assertNotNull(trash.stage(dir))
trash.reap(temp)
trash.drain()
Files.createDirectories(dir)

trashApi.checkReappearance(dir.toString(), temp)
trash.drain()

assertFalse(Files.exists(dir), "a path that reappeared after reap must be staged and reaped once more")
} finally {
scope.cancel()
}
}

@Test
fun `checkReappearance does nothing when the original path did not come back`() = runBlocking {
val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
val trash = WorktreeTrash(scope)
val trashApi = KiloWorktreeRpcApiImpl(trash)
try {
val dir = repo.resolve("gone-for-good")
Files.createDirectories(dir)
val temp = assertNotNull(trash.stage(dir))
trash.reap(temp)
trash.drain()

trashApi.checkReappearance(dir.toString(), temp)
trash.drain()

assertFalse(Files.exists(dir))
assertEquals(0, trash.pending(), "nothing should have been staged again")
} finally {
scope.cancel()
}
}

@Test
fun `staleWorktrees excludes a worktree already marked doomed in WorktreeTrash`() {
val trash = WorktreeTrash(CoroutineScope(Dispatchers.Default + SupervisorJob()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,29 @@ class WorktreeTrashTest {
trash.drain() // must not throw
}

@Test
fun `reap with onDone runs the callback once the delete settles`() = runBlocking {
val dir = root.resolve("${WorktreeTrash.PREFIX}reap-onDone")
Files.createDirectories(dir)
var ran = false

trash.reap(dir) { ran = true }
trash.drain()

assertFalse(Files.exists(dir))
assertTrue(ran, "onDone must run after the reap attempt finishes")
}

@Test
fun `reap with onDone still runs the callback when the directory never existed`() = runBlocking {
var ran = false

trash.reap(root.resolve("${WorktreeTrash.PREFIX}never-existed-onDone")) { ran = true }
trash.drain()

assertTrue(ran, "onDone must run even when there was nothing to delete")
}

@Test
fun `sweep reaps every delete-prefixed directory and ignores ordinary ones`() = runBlocking {
val orphanA = root.resolve("${WorktreeTrash.PREFIX}a").also { Files.createDirectories(it) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ai.kilocode.client.agentManager.worktree.NewWorktreeDialog
import ai.kilocode.client.agentManager.worktree.NewWorktreeHandle
import ai.kilocode.client.agentManager.worktree.NewWorktreePlan
import ai.kilocode.client.agentManager.worktree.GhBanner
import ai.kilocode.client.agentManager.worktree.OrphanBanner
import ai.kilocode.client.agentManager.worktree.WorktreeController
import ai.kilocode.client.agentManager.worktree.WorktreeDataKeys
import ai.kilocode.client.agentManager.worktree.WorktreeIcons
Expand Down Expand Up @@ -47,6 +48,7 @@ import ai.kilocode.client.plugin.KiloBundle
import ai.kilocode.client.session.SessionActivityKind
import ai.kilocode.client.telemetry.Telemetry
import ai.kilocode.client.ui.UiStyle
import ai.kilocode.client.ui.layout.Stack
import ai.kilocode.client.ui.list.ActiveList
import ai.kilocode.client.ui.list.ActiveListBadge
import ai.kilocode.client.ui.list.ActiveListConfig
Expand Down Expand Up @@ -160,6 +162,7 @@ class AgentManagerPanel(
private var dirty: Map<String, WorktreeDirtyDto> = emptyMap()
private var running: Set<String> = emptySet()
private var hovered: String? = null
private var orphanBanner: OrphanBanner? = null

init {
Disposer.register(parent, this)
Expand All @@ -168,7 +171,11 @@ class AgentManagerPanel(
// busy list or a rebuilt model has already dropped the hover the popup was opened from.
list.onScroll = { popup.hideAll() }
isOpaque = true
project?.let { addToTop(GhBanner(it, this)) }
project?.let {
val orphan = OrphanBanner(it, controller, this)
orphanBanner = orphan
addToTop(Stack.vertical().next(GhBanner(it, this)).next(orphan))
}
addToCenter(body())
list.installPopup(group)
sync()
Expand All @@ -187,7 +194,7 @@ class AgentManagerPanel(
project?.service<WorktreeStatusService>()?.refreshPr(force = true, maxAge = 0)
autoRunSetupScript(created)
}
controller.onReload = { sync() }
controller.onReload = { sync(); orphanBanner?.refresh() }
controller.onCreateFailure = { err -> notifyCreateFailed(err) }
controller.onMoveFailure = { err -> notifyMoveFailed(err) }
controller.onRemoveSuccess = { item, index -> onRemoved(item, index) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ 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.OrphanRemoveResultDto
import ai.kilocode.rpc.dto.RemoveOrphansResultDto
import ai.kilocode.rpc.dto.RemoveWorktreeResultDto
import ai.kilocode.rpc.dto.RenameWorktreeResultDto
import ai.kilocode.rpc.dto.WorktreeBranchesDto
Expand Down Expand Up @@ -186,4 +188,31 @@ class KiloWorktreeService internal constructor(
LOG.warn("worktree session list state write failed for $directory", e)
false
}

/** Apparent size of every orphan in [paths]. A failed lookup answers empty, never a partial throw. */
suspend fun orphanSizes(directory: String, paths: List<String>): Map<String, Long> = try {
call { orphanSizes(directory, paths) }
} catch (e: CancellationException) {
// This pass is cancelled whenever the orphan set changes or a delete starts. Rethrow so the
// caller's job actually ends: swallowing it would hand back an empty map that reads exactly
// like a walk that failed, which the banner remembers and stops retrying.
throw e
} catch (e: Exception) {
LOG.warn("worktree orphan sizes failed for $directory", e)
emptyMap()
}

suspend fun removeOrphans(directory: String, paths: List<String>): RemoveOrphansResultDto = try {
call { removeOrphans(directory, paths) }
} catch (e: Exception) {
LOG.warn("worktree orphan remove failed for $directory", e)
RemoveOrphansResultDto(paths.map { OrphanRemoveResultDto(it, ok = false, error = e.message) })
}

suspend fun revealPath(path: String): Boolean = try {
call { revealPath(path) }
} catch (e: Exception) {
LOG.warn("worktree reveal failed for $path", e)
false
}
}
Loading
Loading