diff --git a/.changeset/calm-agents-keep-worktrees.md b/.changeset/calm-agents-keep-worktrees.md new file mode 100644 index 00000000000..44f66ddbb16 --- /dev/null +++ b/.changeset/calm-agents-keep-worktrees.md @@ -0,0 +1,5 @@ +--- +"kilo-code": patch +--- + +Preserve existing Agent Manager worktrees and use deterministic suffixes when explicit branch names collide. diff --git a/packages/kilo-vscode/src/agent-manager/AgentManagerProvider.ts b/packages/kilo-vscode/src/agent-manager/AgentManagerProvider.ts index dd16ecc6098..e104ef2e33b 100644 --- a/packages/kilo-vscode/src/agent-manager/AgentManagerProvider.ts +++ b/packages/kilo-vscode/src/agent-manager/AgentManagerProvider.ts @@ -68,6 +68,7 @@ export class AgentManagerProvider implements Disposable { private gitOps: GitOps private diffs: WorktreeDiffController private staleWorktreeIds = new Set() + private toolRequests = new Set() private cachedWorktreeStats: { type: "agentManager.worktreeStats"; stats: WorktreeStats[] } | undefined private cachedLocalStats: { type: "agentManager.localStats"; stats: LocalStats } | undefined private unsubTool: (() => void) | undefined @@ -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) diff --git a/packages/kilo-vscode/src/agent-manager/WorktreeManager.ts b/packages/kilo-vscode/src/agent-manager/WorktreeManager.ts index ae1d77e05d6..2dac4738c93 100644 --- a/packages/kilo-vscode/src/agent-manager/WorktreeManager.ts +++ b/packages/kilo-vscode/src/agent-manager/WorktreeManager.ts @@ -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}...`) @@ -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 @@ -293,6 +272,46 @@ export class WorktreeManager { } } + private async prepareWorktreePath(worktreePath: string, reuse: boolean): Promise { + 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 { + 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++) { + const branch = `${base}-${suffix}` + if (available(branch)) return branch + } + } + /** * Run `git worktree add` with post-checkout hook tolerance. * diff --git a/packages/kilo-vscode/src/agent-manager/tool-start.ts b/packages/kilo-vscode/src/agent-manager/tool-start.ts index da261902f69..5c7fbb51ca4 100644 --- a/packages/kilo-vscode/src/agent-manager/tool-start.ts +++ b/packages/kilo-vscode/src/agent-manager/tool-start.ts @@ -41,6 +41,7 @@ export interface ToolDeps { name?: string label?: string }) => Promise + claimRequest?: (requestID: string) => boolean cleanupWorktree: (wid: string, dir: string) => Promise setup: (dir: string, branch?: string, id?: string) => Promise createSessionInWorktree: (dir: string, branch: string, id?: string) => Promise @@ -191,6 +192,11 @@ async function worktree( } export async function startFromTool(deps: ToolDeps, req: ToolRequest): Promise { + 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") diff --git a/packages/kilo-vscode/tests/unit/agent-manager-tool-start.test.ts b/packages/kilo-vscode/tests/unit/agent-manager-tool-start.test.ts index 7d1c158bb73..7eff66077c5 100644 --- a/packages/kilo-vscode/tests/unit/agent-manager-tool-start.test.ts +++ b/packages/kilo-vscode/tests/unit/agent-manager-tool-start.test.ts @@ -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() + 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() + 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() + const pending = Promise.withResolvers() + const resume = Promise.withResolvers() + 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, { diff --git a/packages/kilo-vscode/tests/unit/worktree-manager.test.ts b/packages/kilo-vscode/tests/unit/worktree-manager.test.ts index e9787fc6186..f43ce5676c4 100644 --- a/packages/kilo-vscode/tests/unit/worktree-manager.test.ts +++ b/packages/kilo-vscode/tests/unit/worktree-manager.test.ts @@ -723,39 +723,35 @@ describe("WorktreeManager.ensureGitExclude", () => { // --------------------------------------------------------------------------- describe("WorktreeManager.createWorktree branch collision", () => { - /** - * Exercise the retry path in WorktreeManager when `git worktree add -b ` - * 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) }) })