Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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/jetbrains-worktree-safety.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kilocode/kilo-jetbrains": patch
---

Keep JetBrains Agent Manager worktrees in the main repository storage, prevent nested worktree deletion from removing child worktrees, and show a clear missing-folder error for deleted workspaces.
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,10 @@ class KiloWorkspaceRpcApiImpl internal constructor(
status = KiloWorkspaceStatusDto.UNSUPPORTED,
error = state.reason,
)
is KiloWorkspaceState.Missing -> KiloWorkspaceStateDto(
status = KiloWorkspaceStatusDto.MISSING,
error = state.path,
)
is KiloWorkspaceState.Error -> KiloWorkspaceStateDto(
status = KiloWorkspaceStatusDto.ERROR,
error = state.message,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,10 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi {
val res = runGit(base, "worktree", "list", "--porcelain")
if (!res.ok) return@withContext WorktreeListDto()
val items = managedWorktrees(parseWorktreeList(res.stdout))
val store = worktreeNameStore(items)
val state = store?.let { syncWorktreeState(it, worktreePaths(items)) } ?: WorktreeState()
val named = overlayWorktreeNames(items, state.names)
val alive = items.filter { it.main || Files.isDirectory(Path.of(it.path)) }
val store = worktreeNameStore(alive)
val state = store?.let { syncWorktreeState(it, worktreePaths(alive)) } ?: WorktreeState()
val named = overlayWorktreeNames(alive, state.names)
WorktreeListDto(orderWorktrees(named, state.worktreeOrder))
}

Expand Down Expand Up @@ -276,6 +277,14 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi {
return Path.of(lines[0]).normalize() != Path.of(lines[1]).normalize()
}

/** Main working tree for the repo containing [base]; falls back to [base] when git fails. */
private fun mainWorktree(base: Path): Path {
val res = runGit(base, "worktree", "list", "--porcelain")
if (!res.ok) return base
val main = parseWorktreeList(res.stdout).firstOrNull { it.main } ?: return base
return Path.of(main.path).normalize()
}

override suspend fun create(directory: String, request: CreateWorktreeRequestDto): CreateWorktreeResultDto =
withContext(Dispatchers.IO) {
val base = Path.of(directory).normalize()
Expand Down Expand Up @@ -312,7 +321,12 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi {

/** Runs `git worktree add` under `<base>/.kilo/worktrees/<slug>` and records list bookkeeping. */
private fun addWorktree(base: Path, branch: String, existing: Boolean, baseRef: String?): CreateWorktreeResultDto {
val dir = base.resolve(".kilo").resolve("worktrees").resolve(branch.replace('/', '-'))
val root = mainWorktree(base)
val storage = root.resolve(".kilo").resolve("worktrees").normalize()
val parts = branch.split('/')
if (parts.any { it.isBlank() || it == "." || it == ".." }) return CreateWorktreeResultDto(error = "Invalid branch name")
val dir = storage.resolve(branch.replace('/', '-')).normalize()
if (dir.parent != storage) return CreateWorktreeResultDto(error = "Invalid branch name")
Files.createDirectories(dir.parent)
val args = buildList {
addAll(listOf("worktree", "add"))
Expand All @@ -327,7 +341,7 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi {
}
}
LOG.info("worktree add requested: branch=$branch existing=$existing base=${baseRef ?: "(current)"} dir=$dir")
val res = runGit(base, *args.toTypedArray())
val res = add(base, args)
if (!res.ok) {
LOG.warn("worktree add failed: branch=$branch exit=${res.exit} stderr=${res.stderr.trim()}")
return CreateWorktreeResultDto(error = res.stderr.ifBlank { "git worktree add failed" })
Expand All @@ -347,15 +361,42 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi {
val base = Path.of(directory).normalize()
LOG.info("worktree remove requested: path=$path branch=${branch ?: "(none)"} force=$force base=$base")
val list = runGit(base, "worktree", "list", "--porcelain")
val store = (if (list.ok) worktreeNameStore(managedWorktrees(parseWorktreeList(list.stdout))) else null)
?: base.resolve(".kilo").resolve(WORKTREE_NAMES_FILE)
if (!list.ok) return@withContext RemoveWorktreeResultDto(error = list.stderr.ifBlank { "git worktree list failed" })
val all = parseWorktreeList(list.stdout)
val items = managedWorktrees(all)
val main = all.firstOrNull { it.main }
val storage = main?.let { Path.of(it.path).normalize().resolve(".kilo").resolve("worktrees").normalize() }
val target = all.firstOrNull {
val item = Path.of(it.path).normalize()
!it.main && samePath(it.path, path) && item.parent == storage
}
?: return@withContext RemoveWorktreeResultDto(error = "Refusing to remove unmanaged worktree: $path")
// Compare canonical (symlink-resolved) paths: on macOS the temp/repo root is a symlink
// (/var -> /private/var), so a raw startsWith against normalized porcelain paths would miss
// a live child and let `git worktree remove --force` delete it recursively.
val root = realPath(path)
val nested = all.filter {
!it.prunable && Files.isDirectory(Path.of(it.path)) && !samePath(it.path, path) && realPath(it.path).startsWith(root)
}
if (nested.isNotEmpty()) {
val names = nested.joinToString("\n") { it.path }
return@withContext RemoveWorktreeResultDto(error = "Delete nested worktrees first:\n$names")
}
val store = worktreeNameStore(items) ?: base.resolve(".kilo").resolve(WORKTREE_NAMES_FILE)
// Force means the user accepted removing a locked worktree; unlock first so the plain
// remove succeeds. Unlock fails harmlessly when the tree isn't actually locked.
if (force) {
val unlock = runGit(base, "worktree", "unlock", path)
val unlock = runGit(base, "worktree", "unlock", target.path)
if (!unlock.ok) LOG.info("worktree unlock skipped: path=$path exit=${unlock.exit} stderr=${unlock.stderr.trim()}")
}
val res = runGit(base, "worktree", "remove", "--force", path)
// Only skip git's own removal when the checkout directory is actually gone. Git also flags a
// worktree prunable when its admin metadata is stale while the files remain; those must still
// be deleted so a later create of the same slug is not blocked by leftovers.
val res = if (!Files.isDirectory(Path.of(target.path))) {
GitResult(0, "", "")
} else {
runGit(base, "worktree", "remove", "--force", target.path)
}
if (!res.ok) {
val locked = res.stderr.contains("locked working tree", ignoreCase = true)
LOG.warn("worktree remove failed: path=$path locked=$locked exit=${res.exit} stderr=${res.stderr.trim()}")
Expand All @@ -370,7 +411,11 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi {
if (!del.ok) LOG.warn("worktree branch delete failed: branch=$it exit=${del.exit} stderr=${del.stderr.trim()}")
}
LOG.info("worktree removed: path=$path branch=${branch ?: "(none)"}")
removeWorktreeState(store, path)
removeWorktreeState(store, target.path)
val prune = runGit(base, "worktree", "prune")
if (!prune.ok) LOG.warn("worktree prune failed: exit=${prune.exit} stderr=${prune.stderr.trim()}")
runCatching { service<KiloBackendAppService>().workspaces.remove(target.path) }
Comment thread
kirillk marked this conversation as resolved.
Resolved
.onFailure { err -> LOG.info("workspace cache eviction skipped: path=${target.path} message=${err.message}") }
RemoveWorktreeResultDto(ok = true)
}

Expand Down Expand Up @@ -471,6 +516,20 @@ class KiloWorktreeRpcApiImpl : KiloWorktreeRpcApi {
}
}

private fun add(base: Path, args: List<String>): GitResult {
val first = runGit(base, *args.toTypedArray())
if (first.ok || !stale(first.stderr)) return first
val prune = runGit(base, "worktree", "prune")
if (!prune.ok) LOG.warn("worktree prune before retry failed: exit=${prune.exit} stderr=${prune.stderr.trim()}")
return runGit(base, *args.toTypedArray())
}

private fun stale(text: String): Boolean {
return text.contains("is already checked out", ignoreCase = true) ||
text.contains("already used by worktree", ignoreCase = true) ||
text.contains("missing but already registered worktree", ignoreCase = true)
}

private suspend fun <T, R> parallel(items: List<T>, block: suspend (T) -> R): List<R> = coroutineScope {
val sem = Semaphore(4)
items.map { item -> async { sem.withPermit { block(item) } } }.map { it.await() }
Expand Down Expand Up @@ -637,16 +696,18 @@ internal fun parseWorktreeList(raw: String): List<WorktreeDto> {
var branch = "(detached)"
var locked = false
var lockReason: String? = null
var prunable = false
var first = true
fun flush() {
val p = path ?: return
val name = p.substringAfterLast('/').ifBlank { p }
out.add(WorktreeDto(p, name, branch, p, main = first, locked = locked, lockReason = lockReason))
out.add(WorktreeDto(p, name, branch, p, main = first, locked = locked, lockReason = lockReason, prunable = prunable))
first = false
path = null
branch = "(detached)"
locked = false
lockReason = null
prunable = false
}
for (line in raw.lines()) {
when {
Expand All @@ -656,6 +717,7 @@ internal fun parseWorktreeList(raw: String): List<WorktreeDto> {
locked = true
lockReason = line.removePrefix("locked").trim().takeIf { it.isNotEmpty() }
}
line == "prunable" || line.startsWith("prunable ") -> prunable = true
line.isBlank() -> flush()
}
}
Expand All @@ -669,8 +731,9 @@ internal fun managedWorktrees(items: List<WorktreeDto>): List<WorktreeDto> {
val storage = root.resolve(".kilo").resolve("worktrees").normalize()
return items.filter { item ->
if (item.main) return@filter true
if (item.prunable) return@filter false
val path = Path.of(item.path).normalize()
path.startsWith(storage) && path != storage
path.parent == storage
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.atomic.AtomicReference

/**
Expand Down Expand Up @@ -77,6 +79,11 @@ class KiloBackendWorkspace(
_state.value = KiloWorkspaceState.Unsupported(reason)
return@launch
}
if (!Files.isDirectory(Path.of(directory))) {
log.info("Workspace directory is missing: $directory")
_state.value = KiloWorkspaceState.Missing(directory)
return@launch
}
val progress = AtomicReference(KiloWorkspaceLoadProgress())
_state.value = KiloWorkspaceState.Loading(progress.get())

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import ai.kilocode.jetbrains.api.client.DefaultApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharedFlow
import okhttp3.OkHttpClient
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.ConcurrentHashMap

/**
Expand Down Expand Up @@ -74,8 +76,26 @@ class KiloBackendWorkspaceManager(
}
}

/** Remove a workspace (e.g. when a worktree is deleted). */
/**
* Remove any cached workspace whose directory resolves to the same real path as [dir].
* Callers pass git porcelain paths, while workspaces are often keyed by the resolved
* (`toRealPath`) path or the IDE base path, so an exact-string match would miss the entry
* and leave a deleted worktree cached as Ready — still producing backend errors.
*/
fun remove(dir: String) {
workspaces.remove(dir)?.stop()
val target = canonical(dir)
workspaces.keys.filter { canonical(it) == target }.forEach { key ->
log.info("Removing cached workspace for $key")
workspaces.remove(key)?.stop()
}
}

/** Resolve symlinks on the parent so `/var/...` and `/private/var/...` compare equal even after the leaf is deleted. */
private fun canonical(dir: String): String {
val path = Path.of(dir).normalize()
val parent = path.parent ?: return path.toString()
val name = path.fileName ?: return path.toString()
val root = runCatching { if (Files.exists(parent)) parent.toRealPath() else parent }.getOrDefault(parent)
return root.resolve(name).toString()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ sealed class KiloWorkspaceState {
val skills: List<SkillInfo>,
) : KiloWorkspaceState()
data class Unsupported(val reason: String) : KiloWorkspaceState()
data class Missing(val path: String) : KiloWorkspaceState()
data class Error(val message: String, val errors: List<LoadError> = emptyList()) : KiloWorkspaceState()
}

Expand Down
Loading
Loading