-
Notifications
You must be signed in to change notification settings - Fork 3.1k
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 all 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…
bagatao-anaconda fb5f410
fix(cli): prune stale worktree registrations and avoid full app boots…
bagatao-anaconda 8e13ede
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda 2762d09
fix(cli): wait for worktree setup and align --worktree with Agent Man…
bagatao-anaconda 0d78791
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda 627e24d
refactor(cli): tighten tui-worktree implementation and note reuse lim…
bagatao-anaconda f3e93ec
fix(cli): don't force-delete pre-existing branches when reclaiming a …
bagatao-anaconda e6214f7
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda 90989d4
fix(cli): update tui-worktree to use Database.layerFromPath after ups…
bagatao-anaconda 4fdaa4c
refactor(cli): tighten tui-worktree, log exclude-write failures, fix …
bagatao-anaconda 7c25f5b
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda 142575a
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda a8290bf
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda b57cfdc
feat(cli): add kilo worktree create/list/remove commands and TUI alias
bagatao-anaconda aac78b2
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
bagatao-anaconda 914b67e
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda e344cea
fix(cli): lazy-import @/worktree in worktree.ts to unblock cli-shutdo…
bagatao-anaconda 7d74034
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda 91747c0
docs: update worktree-for-cli changeset to cover create/list/remove a…
bagatao-anaconda 8294c69
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda b93b975
fix(cli): use Effect.tryPromise instead of Effect.promise for lazy @/…
bagatao-anaconda 6f9f230
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
bagatao-anaconda 8f70f8f
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda 0af6c2d
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda 6b2a716
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda 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
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. Also adds `kilo worktree create/list/remove` for managing worktrees without launching the TUI, and a `/worktree` command in the TUI to list and remove them. 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,216 @@ | ||
| // 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 * as Log from "@opencode-ai/core/util/log" | ||
| import { UI } from "@/cli/ui" | ||
| import { Filesystem } from "@/util/filesystem" | ||
| import { errorMessage } from "@/util/error" | ||
|
|
||
| const log = Log.create({ service: "kilocode.tui-worktree" }) | ||
|
|
||
| // Matches packages/kilo-vscode/src/agent-manager/WorktreeManager.ts's placement | ||
| // and its ensureGitExclude(), keeping `.kilo/worktrees/` out of `git status`. | ||
| const KILO_WORKTREE_DIR = ".kilo/worktrees" | ||
|
|
||
| // Exported for tests. | ||
| export async function ensureGitExclude(root: string) { | ||
| const excludePath = path.join(root, ".git", "info", "exclude") | ||
| const current = (await Filesystem.readText(excludePath).catch(() => "")).replace(/\s+$/, "") | ||
| if (current.includes(`${KILO_WORKTREE_DIR}/`)) return | ||
| const prefix = current ? `${current}\n\n` : "" | ||
| await Filesystem.write(excludePath, `${prefix}# Kilo Code agent worktrees\n${KILO_WORKTREE_DIR}/\n`).catch((err) => | ||
| log.error("failed to update .git/info/exclude", { excludePath, err }), | ||
| ) | ||
| } | ||
|
|
||
| function samePath(a: string, b: string) { | ||
| return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b | ||
| } | ||
|
|
||
| // Exported for tests. | ||
| export function slugify(name: string) { | ||
| return name | ||
| .trim() | ||
| .toLowerCase() | ||
| .replace(/[^a-z0-9]+/g, "-") | ||
| .replace(/^-+|-+$/g, "") | ||
| } | ||
|
|
||
| // `InstanceStore.Interface.provide` loads (and caches) the instance context and | ||
| // scopes an effect to it; this adds the AppRuntime execution plus 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); `cancel()` drops the timer/listener early. */ | ||
| 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) | ||
| } | ||
| // Not `unref()`'d: it's the only thing keeping the launcher's event loop | ||
| // alive while waiting, so a collected timer would let it exit 0 on a stall. | ||
| 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 } | ||
| } | ||
|
|
||
| // Exported for `kilo worktree create` (worktree.ts), which calls this and | ||
| // exits instead of going on to launch the TUI. | ||
| export 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 { primaryWorktree } = await import("@/kilocode/primary-worktree") | ||
| const { Git } = await import("@/git") | ||
| const slug = slugify(name) | ||
| if (!slug) throw new Error(`Invalid worktree name "${name}"`) | ||
| return withInstance(root, async (run) => { | ||
| const ctx = await run(InstanceState.context) | ||
| // ctx.worktree is whichever checkout the command runs in. Creating under | ||
| // it unconditionally would nest `.kilo/worktrees/<name>` inside another | ||
| // worktree and branch off that worktree's HEAD instead of the primary | ||
| // checkout's — refuse rather than get this wrong. | ||
| const primary = await run(primaryWorktree(ctx.worktree)) | ||
| if (primary && !samePath(primary, ctx.worktree)) | ||
| throw new Error( | ||
| `Cannot create worktree "${slug}" from inside another worktree (${ctx.worktree}). Run this from the primary checkout at ${primary} instead.`, | ||
| ) | ||
|
|
||
| const directory = path.join(ctx.worktree, KILO_WORKTREE_DIR, slug) | ||
| // 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, or pruned). | ||
| const registered = (await run(Worktree.Service.use((svc) => svc.list()))).some((w) => | ||
| samePath(w.directory, directory), | ||
| ) | ||
| const exists = await Filesystem.exists(directory) | ||
|
|
||
| if (registered && exists) { | ||
| // Assumes whatever created it already finished setting up; a worktree | ||
| // still booting when its own process was interrupted won't be detected. | ||
| 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 run would need to, so the name is free to reuse. | ||
| if (registered) { | ||
| await run(Worktree.Service.use((svc) => svc.remove({ directory }))).catch((error) => { | ||
| throw new Error(`Failed to reclaim stale worktree "${slug}": ${errorMessage(error)}`) | ||
| }) | ||
| } | ||
|
|
||
| // `createFromInfo` below passes `branch: slug` straight to `git worktree | ||
| // add -b`, which fails outright if that branch already exists — e.g. one | ||
| // left behind by `git worktree prune` (which drops the registration but | ||
| // never deletes the branch). Clear it first so the name can be reused, but | ||
| // only with `-d` (not `-D`): it refuses unless the branch is fully merged, | ||
| // so we never silently discard unmerged work from an interrupted worktree | ||
| // or an unrelated branch that happens to share the name. | ||
| const runGit = (args: string[]) => run(Git.Service.use((git) => git.run(args, { cwd: ctx.worktree }))) | ||
| const branchRef = await runGit(["show-ref", "--verify", "--quiet", `refs/heads/${slug}`]) | ||
| if (branchRef.exitCode === 0) { | ||
|
bagatao-anaconda marked this conversation as resolved.
|
||
| const deleted = await runGit(["branch", "-d", slug]) | ||
| if (deleted.exitCode !== 0) { | ||
| const message = deleted.stderr.toString("utf8").trim() || deleted.text().trim() | ||
| throw new Error( | ||
| `Branch "${slug}" already exists${message ? ` (${message})` : ""}. Remove it (e.g. \`git branch -D ${slug}\` if you're sure it's safe to discard) and retry.`, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| 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( | ||
|
bagatao-anaconda marked this conversation as 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.layerFromPath(Database.path())), | ||
| ), | ||
| ) | ||
| 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) { | ||
|
bagatao-anaconda marked this conversation as 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| // kilocode_change - new file | ||
| // `kilo worktree list`/`remove`: CLI-side counterpart to `kilo --worktree <name>` | ||
| // (tui-worktree.ts) and the TUI's `/worktree` alias for the workspaces dialog | ||
| // (packages/tui/src/app.tsx). All three go through the same `Worktree.Service`. | ||
| import path from "path" | ||
| import { Effect } from "effect" | ||
| import { cmd } from "@/cli/cmd/cmd" | ||
| import { CliError, effectCmd, fail } from "@/cli/effect-cmd" | ||
| import { UI } from "@/cli/ui" | ||
| import { errorMessage } from "@/util/error" | ||
| import { slugify } from "@/kilocode/cli/cmd/tui-worktree" | ||
|
|
||
| const wrapErr = (message: string) => <A, E, R>(effect: Effect.Effect<A, E, R>) => | ||
| effect.pipe(Effect.mapError((error) => new CliError({ message: `${message}: ${errorMessage(error)}` }))) | ||
|
|
||
| // Lazy: this module is imported eagerly by KiloCli.register (see setup.ts), so | ||
| // `@/worktree`'s heavier transitive graph (Project, Provider, ...) must not | ||
| // load until a handler actually runs, matching tui-worktree.ts's own imports. | ||
| // `tryPromise` (not `promise`): a failed dynamic import must flow through each | ||
| // call site's own `wrapErr`, not become an unrecoverable defect. | ||
| const importWorktree = Effect.tryPromise(() => import("@/worktree")) | ||
|
|
||
| const listWorktrees = importWorktree.pipe( | ||
| Effect.flatMap(({ Worktree }) => Worktree.Service.use((svc) => svc.list())), | ||
| wrapErr("Failed to list worktrees"), | ||
| ) | ||
|
|
||
| export const WorktreeCommand = cmd({ | ||
| command: "worktree", | ||
| describe: "manage git worktrees", | ||
| builder: (yargs) => | ||
| yargs.command(WorktreeCreateCommand).command(WorktreeListCommand).command(WorktreeRemoveCommand).demandCommand(), | ||
| async handler() {}, | ||
| }) | ||
|
|
||
| export const WorktreeCreateCommand = cmd({ | ||
| command: "create <name>", | ||
| describe: "create (or reuse) a git worktree by name", | ||
| builder: (yargs) => yargs.positional("name", { type: "string", demandOption: true }), | ||
| async handler(args) { | ||
| // Plain cmd(), not effectCmd(): resolveWorktree loads/disposes its own | ||
| // instance context (it's shared with `kilo --worktree`'s pre-TUI-launch | ||
| // path in tui-worktree.ts), so it can't run inside effectCmd's own. | ||
| const { resolveWorktree } = await import("@/kilocode/cli/cmd/tui-worktree") | ||
| const directory = await resolveWorktree(args.name, process.cwd()).catch((error) => { | ||
| UI.error(errorMessage(error)) | ||
| process.exitCode = 1 | ||
| }) | ||
| // Prints only the resolved path on stdout (status messages already went | ||
| // to stderr via resolveWorktree's own UI.println calls), so scripts can | ||
| // do e.g. `cd "$(kilo worktree create foo)"`. | ||
| if (directory) console.log(directory) | ||
| }, | ||
| }) | ||
|
|
||
| export const WorktreeListCommand = effectCmd({ | ||
| command: "list", | ||
| describe: "list git worktrees for the current project", | ||
| handler: Effect.fn("Cli.worktree.list")(function* () { | ||
| const list = yield* listWorktrees | ||
| if (!list.length) { | ||
| UI.println("No worktrees found.") | ||
| return | ||
| } | ||
| // Data rows go to stdout (like `kilo session list`'s table/JSON), not | ||
| // UI.println's stderr, so `kilo worktree list | ...` actually captures them. | ||
| for (const w of list) console.log(`${w.name}${w.branch ? ` (${w.branch})` : ""} ${w.directory}`) | ||
| }), | ||
| }) | ||
|
|
||
| export const WorktreeRemoveCommand = effectCmd({ | ||
| command: "remove <name>", | ||
| // Worktree.Service.remove() force-deletes (`git branch -D`) the worktree's | ||
| // branch too, with no way to opt out (matches the TUI workspaces dialog's | ||
| // existing semantics) — make that explicit rather than surprise users. | ||
| describe: "remove a git worktree by name, deleting its branch too", | ||
| builder: (yargs) => yargs.positional("name", { type: "string", demandOption: true }), | ||
| handler: Effect.fn("Cli.worktree.remove")(function* (args) { | ||
| const slug = slugify(args.name) | ||
| if (!slug) { | ||
| yield* fail(`Invalid worktree name "${args.name}"`) | ||
| return | ||
| } | ||
| const list = yield* listWorktrees | ||
| // Matches the reuse logic in tui-worktree.ts: list() remaps `name` to the | ||
| // project ID when a worktree's basename collides with the primary | ||
| // checkout's, so also match on the directory basename. | ||
| const found = list.find((w) => w.name.toLowerCase() === slug || path.basename(w.directory).toLowerCase() === slug) | ||
| if (!found) { | ||
| yield* fail(`No worktree named "${args.name}" found.`) | ||
| return | ||
| } | ||
| const removeMsg = `Failed to remove worktree "${args.name}"` | ||
| const { Worktree } = yield* importWorktree.pipe(wrapErr(removeMsg)) | ||
| yield* Worktree.Service.use((svc) => svc.remove({ directory: found.directory })).pipe(wrapErr(removeMsg)) | ||
| const branchNote = found.branch ? ` and branch "${found.branch}"` : "" | ||
| UI.println(`Removed worktree "${found.name}" at ${found.directory}${branchNote}`) | ||
| }), | ||
| }) |
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
Oops, something went wrong.
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.