Repository navigation
feat(cli): add --worktree flag to create/reuse a git worktree for the TUI #12809
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
907f7df
feat(cli): add --worktree flag to create/reuse a git worktree for the…
brunoagatao fb5f410
fix(cli): prune stale worktree registrations and avoid full app boots…
brunoagatao 8e13ede
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao 2762d09
fix(cli): wait for worktree setup and align --worktree with Agent Man…
brunoagatao 0d78791
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao 627e24d
refactor(cli): tighten tui-worktree implementation and note reuse lim…
brunoagatao f3e93ec
fix(cli): don't force-delete pre-existing branches when reclaiming a …
brunoagatao e6214f7
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao 90989d4
fix(cli): update tui-worktree to use Database.layerFromPath after ups…
brunoagatao 4fdaa4c
refactor(cli): tighten tui-worktree, log exclude-write failures, fix …
brunoagatao 7c25f5b
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao 142575a
Merge branch 'main' into feat/worktree-for-cli
brunoagatao a8290bf
Merge branch 'main' into feat/worktree-for-cli
brunoagatao b57cfdc
feat(cli): add kilo worktree create/list/remove commands and TUI alias
brunoagatao aac78b2
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
brunoagatao 914b67e
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao e344cea
fix(cli): lazy-import @/worktree in worktree.ts to unblock cli-shutdo…
brunoagatao 7d74034
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao 91747c0
docs: update worktree-for-cli changeset to cover create/list/remove a…
brunoagatao 8294c69
Merge branch 'main' into feat/worktree-for-cli
brunoagatao b93b975
fix(cli): use Effect.tryPromise instead of Effect.promise for lazy @/…
brunoagatao 6f9f230
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
brunoagatao 8f70f8f
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao 0af6c2d
Merge branch 'main' into feat/worktree-for-cli
brunoagatao 6b2a716
Merge branch 'main' into feat/worktree-for-cli
brunoagatao File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@kilocode/cli": minor | ||
| --- | ||
|
|
||
| Add `kilo --worktree <name>` to create (or reuse) a git worktree and start the TUI there, placed at `.kilo/worktrees/<name>` alongside worktrees created by the VS Code extension's Agent Manager. Resuming an explicit `--session <id>` now tries to restart in the worktree the session was originally created in, if it still exists. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| // kilocode_change - new file | ||
| // Supports `kilo --worktree <name>` (create/reuse a git worktree before the TUI | ||
| // starts, placed at `.kilo/worktrees/<name>` to match Agent Manager's own | ||
| // worktrees) and resuming an explicit `--session <id>` in the worktree it was | ||
| // created in. | ||
| import path from "path" | ||
| import type { Effect } from "effect" | ||
| import { UI } from "@/cli/ui" | ||
| import { Filesystem } from "@/util/filesystem" | ||
| import { errorMessage } from "@/util/error" | ||
|
|
||
| // Matches packages/kilo-vscode/src/agent-manager/WorktreeManager.ts's placement. | ||
| const KILO_WORKTREE_DIR = ".kilo/worktrees" | ||
|
|
||
| // Mirrors WorktreeManager.ts's ensureGitExclude(): keeps `.kilo/worktrees/` | ||
| // out of `git status` for repos Agent Manager hasn't touched yet. | ||
| // Exported for unit testing; not part of the module's public contract. | ||
| export async function ensureGitExclude(root: string) { | ||
| const excludePath = path.join(root, ".git", "info", "exclude") | ||
| const current = await Filesystem.readText(excludePath).catch(() => "") | ||
| if (current.includes(`${KILO_WORKTREE_DIR}/`)) return | ||
| const separator = current.length && !current.endsWith("\n") ? "\n" : "" | ||
| await Filesystem.write( | ||
| excludePath, | ||
| `${current}${separator}\n# Kilo Code agent worktrees\n${KILO_WORKTREE_DIR}/\n`, | ||
| ).catch(() => {}) | ||
| } | ||
|
|
||
| function samePath(a: string, b: string) { | ||
| return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b | ||
| } | ||
|
|
||
| // Exported for unit testing; not part of the module's public contract. | ||
| export function slugify(name: string) { | ||
| return name | ||
| .trim() | ||
| .toLowerCase() | ||
| .replace(/[^a-z0-9]+/g, "-") | ||
| .replace(/^-+|-+$/g, "") | ||
| } | ||
|
|
||
| // `InstanceStore.Interface.provide` already loads the instance context and | ||
| // scopes an effect to it; this just adds the AppRuntime execution and a | ||
| // matching `disposeDirectory` once the caller is done with `root`. | ||
| async function withInstance<A>(root: string, fn: (run: <T>(effect: Effect.Effect<T, any, any>) => Promise<T>) => Promise<A>) { | ||
| const { AppRuntime } = await import("@/effect/app-runtime") | ||
| const { InstanceStore } = await import("@/project/instance-store") | ||
| const run = <T>(effect: Effect.Effect<T, any, any>) => | ||
| AppRuntime.runPromise(InstanceStore.Service.use((store) => store.provide({ directory: root }, effect))) | ||
| try { | ||
| return await fn(run) | ||
| } finally { | ||
| await AppRuntime.runPromise(InstanceStore.Service.use((store) => store.disposeDirectory(root))) | ||
| } | ||
| } | ||
|
|
||
| type WaitResult = { ok: true } | { ok: false; message: string } | ||
|
|
||
| /** Waits for `directory`'s `worktree.setup.ready`/`worktree.failed` event (full | ||
| * readiness, not just checkout), with a `cancel()` to drop the timer/listener | ||
| * on early failure. */ | ||
| function waitForWorktreeEvent( | ||
| bus: typeof import("@/bus/global").GlobalBus, | ||
| event: typeof import("@/worktree").Worktree.Event, | ||
| directory: string, | ||
| timeoutMs: number, | ||
| ) { | ||
| const deferred = Promise.withResolvers<WaitResult>() | ||
| let handler = (_e: { directory?: string; payload?: any }) => {} | ||
| const cleanup = () => { | ||
| clearTimeout(timer) | ||
| bus.off("event", handler) | ||
| } | ||
| // Intentionally not `unref()`'d: this timer is the timeout guarantee for a | ||
| // launcher process that has nothing else keeping the event loop alive, so | ||
| // letting it be collected would let the process exit 0 on a stalled boot. | ||
| const timer = setTimeout(() => { | ||
| cleanup() | ||
| deferred.resolve({ ok: false, message: "Timed out waiting for the worktree to finish setting up" }) | ||
| }, timeoutMs) | ||
| handler = (e) => { | ||
| if (e.directory !== directory) return | ||
| if (e.payload?.type === event.SetupReady.type) { | ||
| cleanup() | ||
| deferred.resolve({ ok: true }) | ||
| } else if (e.payload?.type === event.Failed.type) { | ||
| cleanup() | ||
| deferred.resolve({ ok: false, message: e.payload.properties?.message ?? "Worktree setup failed" }) | ||
| } | ||
| } | ||
| bus.on("event", handler) | ||
| return { promise: deferred.promise, cancel: cleanup } | ||
| } | ||
|
|
||
| async function resolveWorktree(name: string, root: string, timeoutMs = 10 * 60_000) { | ||
| const { Worktree } = await import("@/worktree") | ||
| const { GlobalBus } = await import("@/bus/global") | ||
| const { InstanceState } = await import("@/effect/instance-state") | ||
| const slug = slugify(name) | ||
| if (!slug) throw new Error(`Invalid worktree name "${name}"`) | ||
| return withInstance(root, async (run) => { | ||
| const ctx = await run(InstanceState.context) | ||
| const directory = path.join(ctx.worktree, KILO_WORKTREE_DIR, slug) | ||
|
brunoagatao marked this conversation as resolved.
Resolved
|
||
|
|
||
| // Trust neither signal alone: a directory can exist without a live git | ||
| // registration (orphaned), and a registration can outlive its directory | ||
| // (deleted out-of-band). | ||
| const existing = await run(Worktree.Service.use((svc) => svc.list())) | ||
| const registered = existing.some((w) => samePath(w.directory, directory)) | ||
| const exists = await Filesystem.exists(directory) | ||
|
|
||
| if (registered && exists) { | ||
| if (!(await Filesystem.exists(path.join(directory, ".git")))) { | ||
| throw new Error(`"${directory}" is registered but was never fully checked out. Remove it and retry.`) | ||
| } | ||
| UI.println(`Using existing worktree "${slug}" at ${directory}`) | ||
| return directory | ||
| } | ||
| if (exists) throw new Error(`"${directory}" already exists but is not a registered git worktree.`) | ||
| // Registered but missing: reclaim the dead registration (and its branch) | ||
| // the same way a fresh `--worktree <name>` run would need to, so the name | ||
| // is free to reuse below. | ||
| if (registered) { | ||
| await run(Worktree.Service.use((svc) => svc.remove({ directory }))).catch((error) => { | ||
|
brunoagatao marked this conversation as resolved.
Resolved
|
||
| throw new Error(`Failed to reclaim stale worktree "${slug}": ${errorMessage(error)}`) | ||
| }) | ||
| } | ||
|
|
||
| await ensureGitExclude(ctx.worktree) | ||
| UI.println(`Creating worktree "${slug}"...`) | ||
| const wait = waitForWorktreeEvent(GlobalBus, Worktree.Event, directory, timeoutMs) | ||
| await run(Worktree.Service.use((svc) => svc.createFromInfo({ name: slug, branch: slug, directory }))).catch( | ||
|
brunoagatao marked this conversation as resolved.
Resolved
|
||
| (error) => { | ||
| wait.cancel() | ||
| throw error | ||
| }, | ||
| ) | ||
| const result = await wait.promise | ||
| if (!result.ok) throw new Error(`Failed to create worktree "${slug}": ${result.message}`) | ||
| UI.println(`Worktree ready at ${directory}`) | ||
| return directory | ||
| }) | ||
| } | ||
|
|
||
| // Reads only the session's `directory` column against a throwaway | ||
| // Database-only layer instead of the full AppRuntime (Plugin/LSP/MCP/Provider/ | ||
| // Observability/etc), since `--session <id>` is common and shouldn't pay for | ||
| // bootstrapping the whole app graph in the launcher process just for this. | ||
| async function resolveSessionWorktree(sessionID: string, fallback: string) { | ||
| try { | ||
| const { Effect, Schema } = await import("effect") | ||
| const { Database } = await import("@opencode-ai/core/database/database") | ||
| const { SessionTable } = await import("@opencode-ai/core/session/sql") | ||
| const { eq } = await import("drizzle-orm") | ||
| const { SessionID } = await import("@/session/schema") | ||
| const id = Schema.decodeUnknownSync(SessionID)(sessionID) | ||
| const row = await Effect.runPromise( | ||
| Database.Service.use(({ db }) => db.select().from(SessionTable).where(eq(SessionTable.id, id)).get()).pipe( | ||
| Effect.provide(Database.defaultLayer), | ||
| ), | ||
| ) | ||
| const directory = row?.directory | ||
| if (!directory || directory === fallback) return fallback | ||
| if (!(await Filesystem.exists(directory))) return fallback | ||
| UI.println(`Resuming session in its original worktree: ${directory}`) | ||
| return directory | ||
| } catch { | ||
| // Unknown session, missing directory, or lookup failure: fall back to the | ||
| // resolved cwd and let normal session validation report the real error. | ||
| return fallback | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Resolves the directory to launch the TUI in: creates/reuses `--worktree | ||
| * <name>`, or when resuming an explicit `--session <id>` without `--project`, | ||
| * tries that session's original worktree. Otherwise returns `root` unchanged. | ||
| */ | ||
| export function resolveTuiDirectory(args: { worktree?: string; session?: string; project?: string }, root: string) { | ||
|
brunoagatao marked this conversation as resolved.
Resolved
|
||
| if (args.worktree) return resolveWorktree(args.worktree, root) | ||
| if (args.session && !args.project) return resolveSessionWorktree(args.session, root) | ||
| return Promise.resolve(root) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 67 additions & 0 deletions
67
packages/opencode/test/kilocode/cli/cmd/tui-worktree.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import { describe, expect, test } from "bun:test" | ||
| import path from "path" | ||
| import { mkdtemp, rm } from "fs/promises" | ||
| import { tmpdir as osTmpdir } from "os" | ||
| import { ensureGitExclude, slugify } from "@/kilocode/cli/cmd/tui-worktree" | ||
| import { Filesystem } from "@/util/filesystem" | ||
|
|
||
| describe("slugify", () => { | ||
| test("lowercases and dashes non-alphanumeric runs", () => { | ||
| expect(slugify("My Feature!")).toBe("my-feature") | ||
| expect(slugify("fix_bug--123")).toBe("fix-bug-123") | ||
| }) | ||
|
|
||
| test("trims leading/trailing dashes", () => { | ||
| expect(slugify("--hello--")).toBe("hello") | ||
| }) | ||
|
|
||
| test("returns empty for names with no alphanumeric characters", () => { | ||
| expect(slugify("!!!")).toBe("") | ||
| expect(slugify(" ")).toBe("") | ||
| }) | ||
| }) | ||
|
|
||
| describe("ensureGitExclude", () => { | ||
| async function withRepo(fn: (root: string) => Promise<void>) { | ||
| const root = await mkdtemp(path.join(osTmpdir(), "tui-worktree-exclude-")) | ||
| try { | ||
| await fn(root) | ||
| } finally { | ||
| await rm(root, { recursive: true, force: true }) | ||
| } | ||
| } | ||
|
|
||
| test("appends the exclude entry when the file exists but is empty", () => | ||
| withRepo(async (root) => { | ||
| const excludePath = path.join(root, ".git", "info", "exclude") | ||
| await Filesystem.write(excludePath, "") | ||
| await ensureGitExclude(root) | ||
| const content = await Filesystem.readText(excludePath) | ||
| expect(content).toContain(".kilo/worktrees/") | ||
| })) | ||
|
|
||
| test("preserves existing content and adds a newline before the new entry", () => | ||
| withRepo(async (root) => { | ||
| const excludePath = path.join(root, ".git", "info", "exclude") | ||
| await Filesystem.write(excludePath, "*.log") | ||
| await ensureGitExclude(root) | ||
| const content = await Filesystem.readText(excludePath) | ||
| expect(content).toContain("*.log") | ||
| expect(content).toContain(".kilo/worktrees/") | ||
| })) | ||
|
|
||
| test("is idempotent when the entry already exists", () => | ||
| withRepo(async (root) => { | ||
| const excludePath = path.join(root, ".git", "info", "exclude") | ||
| await Filesystem.write(excludePath, "") | ||
| await ensureGitExclude(root) | ||
| await ensureGitExclude(root) | ||
| const content = await Filesystem.readText(excludePath) | ||
| expect(content.match(/\.kilo\/worktrees\//g)?.length).toBe(1) | ||
| })) | ||
|
|
||
| test("does not throw when .git/info is missing", () => | ||
| withRepo(async (root) => { | ||
| await ensureGitExclude(root) | ||
| })) | ||
| }) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.