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/calm-agents-keep-worktrees.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Preserve existing Agent Manager worktrees and use deterministic suffixes when explicit branch names collide.
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export class AgentManagerProvider implements Disposable {
private gitOps: GitOps
private diffs: WorktreeDiffController
private staleWorktreeIds = new Set<string>()
private toolRequests = new Set<string>()
private cachedWorktreeStats: { type: "agentManager.worktreeStats"; stats: WorktreeStats[] } | undefined
private cachedLocalStats: { type: "agentManager.localStats"; stats: LocalStats } | undefined
private unsubTool: (() => void) | undefined
Expand Down Expand Up @@ -910,6 +911,13 @@ export class AgentManagerProvider implements Disposable {
openPanel: (preserveFocus) => this.openPanel(preserveFocus),
waitReady: (context) => this.waitForStateReady(context),
createWorktree: (opts) => this.createWorktreeOnDisk(opts),
claimRequest: (id) => {
if (this.toolRequests.has(id)) return false
const oldest = this.toolRequests.size >= 100 ? this.toolRequests.values().next().value : undefined
if (oldest) this.toolRequests.delete(oldest)
this.toolRequests.add(id)
return true
},
cleanupWorktree: async (wid, dir) => {
this.getStateManager()?.removeWorktree(wid)
await this.getWorktreeManager()?.removeWorktree(dir)
Expand Down
69 changes: 44 additions & 25 deletions packages/kilo-vscode/src/agent-manager/WorktreeManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,32 +222,11 @@ export class WorktreeManager {
parentRemote = startPoint.remote
}

const sanitized = params.branchName ? sanitizeBranchName(params.branchName) : undefined
let branch: string
if (params.existingBranch) {
branch = params.existingBranch
} else if (sanitized) {
branch = sanitized
} else {
const existing = await this.git
.branch()
.then((b) => b.all)
.catch(() => [] as string[])
branch = generateBranchName(params.prompt || "agent-task", existing)
}

if (params.existingBranch) {
const exists = await this.branchExists(branch)
if (!exists) throw new Error(`Branch "${branch}" does not exist`)
}

let branch = await this.resolveBranch(params)
const dirName = branch.replace(/\//g, "-")
let worktreePath = path.join(this.dir, dirName)

if (fs.existsSync(worktreePath)) {
this.log(`Worktree directory exists, cleaning up before re-creation: ${worktreePath}`)
await this.removeWorktreeImpl(worktreePath)
}
await this.prepareWorktreePath(worktreePath, !!params.existingBranch)

params.onProgress?.("creating", `Creating worktree for ${branch}...`)

Expand All @@ -270,8 +249,8 @@ export class WorktreeManager {
if (!msg.includes("already exists") || params.existingBranch) {
throw new Error(`Failed to create worktree: ${msg}`)
}
// Branch name collision -- retry with unique suffix
branch = `${branch}-${Date.now()}`
// Another process may create the branch after resolveBranch checks it.
branch = await this.resolveBranch(params)
const retryDir = branch.replace(/\//g, "-")
worktreePath = path.join(this.dir, retryDir)
const retryArgs = params.existingBranch
Expand All @@ -293,6 +272,46 @@ export class WorktreeManager {
}
}

private async prepareWorktreePath(worktreePath: string, reuse: boolean): Promise<void> {
if (!fs.existsSync(worktreePath)) return
if (!reuse) throw new Error(`Worktree path already exists: ${worktreePath}`)
this.log(`Worktree directory exists, cleaning up before re-creation: ${worktreePath}`)
await this.removeWorktreeImpl(worktreePath)
}

private async resolveBranch(params: {
prompt?: string
existingBranch?: string
branchName?: string
}): Promise<string> {
if (params.existingBranch) {
const exists = await this.branchExists(params.existingBranch)
if (!exists) throw new Error(`Branch "${params.existingBranch}" does not exist`)
return params.existingBranch
}

const existing = await this.git
.branch()
.then((result) => result.all)
.catch(() => [] as string[])
const sanitized = params.branchName ? sanitizeBranchName(params.branchName) : undefined
const branch = sanitized || generateBranchName(params.prompt || "agent-task", existing)
return this.availableBranch(branch, existing)
}

private availableBranch(base: string, existing: string[]): string {
const branches = new Set(existing)
const available = (branch: string) => {
const dir = path.join(this.dir, branch.replace(/\//g, "-"))
return !branches.has(branch) && !fs.existsSync(dir)
}
if (available(base)) return base
for (let suffix = 2; ; suffix++) {
Comment thread
marius-kilocode marked this conversation as resolved.
Resolved
const branch = `${base}-${suffix}`
if (available(branch)) return branch
}
}

/**
* Run `git worktree add` with post-checkout hook tolerance.
*
Expand Down
6 changes: 6 additions & 0 deletions packages/kilo-vscode/src/agent-manager/tool-start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export interface ToolDeps {
name?: string
label?: string
}) => Promise<WorktreeCreated | null>
claimRequest?: (requestID: string) => boolean
cleanupWorktree: (wid: string, dir: string) => Promise<void>
setup: (dir: string, branch?: string, id?: string) => Promise<void>
createSessionInWorktree: (dir: string, branch: string, id?: string) => Promise<Session | null>
Expand Down Expand Up @@ -191,6 +192,11 @@ async function worktree(
}

export async function startFromTool(deps: ToolDeps, req: ToolRequest): Promise<void> {
if (deps.claimRequest && !deps.claimRequest(req.requestID)) {
deps.log(`Agent Manager tool skipped duplicate request ${req.requestID}`)
return
}

deps.openPanel(true)
await deps.getPanel()?.waitForReady()
await deps.waitReady("startFromTool")
Expand Down
91 changes: 91 additions & 0 deletions packages/kilo-vscode/tests/unit/agent-manager-tool-start.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,97 @@ describe("agent manager tool start", () => {
expect(c.notifyReady).toHaveBeenCalled()
})

it("deduplicates repeated delivery of the same exact request", async () => {
const requests = new Set<string>()
const c = deps({
claimRequest: mock((id: string) => {
if (requests.has(id)) return false
requests.add(id)
return true
}),
})
const req: ToolRequest = {
requestID: "am-duplicate",
mode: "worktree",
tasks: [
{
branchName: "echo-hello-world",
name: "Echo hello world",
prompt: 'Use the bash tool to run: echo "hello world". Report back the output.',
},
],
}

await startFromTool(c, req)
await startFromTool(c, req)

expect(c.createWorktree).toHaveBeenCalledTimes(1)
expect(c.createSessionInWorktree).toHaveBeenCalledTimes(1)
})

it("starts each task from separate tool calls even when their branch seeds match", async () => {
const requests = new Set<string>()
const c = deps({
claimRequest: mock((id: string) => {
if (requests.has(id)) return false
requests.add(id)
return true
}),
})
const req: ToolRequest = {
requestID: "am-first",
mode: "worktree",
tasks: [
{
branchName: "echo-hello-world",
name: "Echo hello world",
prompt: 'Use the bash tool to run: echo "hello world". Report back the output.',
},
],
}

await startFromTool(c, req)
await startFromTool(c, { ...req, requestID: "am-second" })

expect(c.createWorktree).toHaveBeenCalledTimes(2)
expect(c.createSessionInWorktree).toHaveBeenCalledTimes(2)
expect(c.createWorktree).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ branchName: "echo-hello-world", name: "echo-hello-world" }),
)
})

it("deduplicates concurrent delivery of the same request", async () => {
const requests = new Set<string>()
const pending = Promise.withResolvers<void>()
const resume = Promise.withResolvers<void>()
const c = deps({
claimRequest: mock((id: string) => {
if (requests.has(id)) return false
requests.add(id)
return true
}),
createWorktree: mock(async () => {
pending.resolve()
await resume.promise
return { worktree: { id: "wt-1" }, result: result("/repo/.kilo/worktrees/wt-1") }
}),
})
const req: ToolRequest = {
requestID: "am-concurrent",
mode: "worktree",
tasks: [{ prompt: "Fix", branchName: "fix/concurrent" }],
}

const first = startFromTool(c, req)
await pending.promise
await startFromTool(c, req)
resume.resolve()
await first

expect(c.createWorktree).toHaveBeenCalledTimes(1)
})

it("only applies version suffixes when versions is true", async () => {
const normal = deps()
await startFromTool(normal, {
Expand Down
44 changes: 20 additions & 24 deletions packages/kilo-vscode/tests/unit/worktree-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -723,39 +723,35 @@ describe("WorktreeManager.ensureGitExclude", () => {
// ---------------------------------------------------------------------------

describe("WorktreeManager.createWorktree branch collision", () => {
/**
* Exercise the retry path in WorktreeManager when `git worktree add -b <name>`
* fails because a branch with that name already exists.
*
* We force the collision by creating a worktree with branchName "collide",
* removing the worktree (keeping the branch), then requesting the same
* branchName again.
*/
it("retries with a unique suffix when generated branch name collides", async () => {
it("creates a suffixed worktree without replacing an active explicitly named worktree", async () => {
const root = await createTempRepo()
const git = simpleGit(root)
const mgr = createManager(root)
const first = await mgr.createWorktree({ branchName: "echo-hello-world" })
const second = await mgr.createWorktree({ branchName: "echo-hello-world" })

expect(first.branch).toBe("echo-hello-world")
expect(second.branch).toBe("echo-hello-world-2")
expect((await fs.stat(path.join(first.path, ".git"))).isFile()).toBe(true)
expect((await fs.stat(path.join(second.path, ".git"))).isFile()).toBe(true)
expect((await simpleGit(root).branch()).all.filter((branch) => branch.startsWith("echo-hello-world"))).toEqual([
"echo-hello-world",
"echo-hello-world-2",
])
})

// Create a first worktree with a fixed branch name
it("uses the same suffix sequence when only the requested branch already exists", async () => {
const root = await createTempRepo()
const git = simpleGit(root)
const mgr = createManager(root)
const first = await mgr.createWorktree({ branchName: "collide" })
expect(first.branch).toBe("collide")

// Remove the worktree via git but keep the branch ref alive
await git.raw(["worktree", "remove", "--force", first.path])
expect((await git.branch()).all).toContain("collide")

// Verify the branch still exists (worktree is gone, branch is not)
const branches = await git.branch()
expect(branches.all).toContain("collide")

// Request the same branchName — git will fail, triggering the retry
const second = await mgr.createWorktree({ branchName: "collide" })

// The retry appends a timestamp suffix, so the branch name differs
expect(second.branch).not.toBe("collide")
expect(second.branch).toStartWith("collide-")

const stat = await fs.stat(path.join(second.path, ".git"))
expect(stat.isFile()).toBe(true)
expect(second.branch).toBe("collide-2")
expect((await fs.stat(path.join(second.path, ".git"))).isFile()).toBe(true)
})
})

Expand Down
Loading