Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 Aug 3, 2026
fb5f410
fix(cli): prune stale worktree registrations and avoid full app boots…
brunoagatao Aug 3, 2026
8e13ede
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 3, 2026
2762d09
fix(cli): wait for worktree setup and align --worktree with Agent Man…
brunoagatao Aug 4, 2026
0d78791
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 4, 2026
627e24d
refactor(cli): tighten tui-worktree implementation and note reuse lim…
brunoagatao Aug 4, 2026
f3e93ec
fix(cli): don't force-delete pre-existing branches when reclaiming a …
brunoagatao Aug 5, 2026
e6214f7
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 5, 2026
90989d4
fix(cli): update tui-worktree to use Database.layerFromPath after ups…
brunoagatao Aug 5, 2026
4fdaa4c
refactor(cli): tighten tui-worktree, log exclude-write failures, fix …
brunoagatao Aug 5, 2026
7c25f5b
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 5, 2026
142575a
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 6, 2026
a8290bf
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 6, 2026
b57cfdc
feat(cli): add kilo worktree create/list/remove commands and TUI alias
brunoagatao Aug 6, 2026
aac78b2
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
brunoagatao Aug 6, 2026
914b67e
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 6, 2026
e344cea
fix(cli): lazy-import @/worktree in worktree.ts to unblock cli-shutdo…
brunoagatao Aug 6, 2026
7d74034
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 6, 2026
91747c0
docs: update worktree-for-cli changeset to cover create/list/remove a…
brunoagatao Aug 6, 2026
8294c69
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 7, 2026
b93b975
fix(cli): use Effect.tryPromise instead of Effect.promise for lazy @/…
brunoagatao Aug 7, 2026
6f9f230
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
brunoagatao Aug 7, 2026
8f70f8f
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 7, 2026
0af6c2d
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 12, 2026
6b2a716
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 13, 2026
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/worktree-for-cli.md
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. Resuming an explicit `--session <id>` now tries to restart in the worktree the session was originally created in, if it still exists.
16 changes: 15 additions & 1 deletion packages/opencode/src/cli/cmd/tui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,12 @@ export const TuiThreadCommand = cmd({
type: "boolean",
describe: "fetch session from cloud and continue locally (use with --session)",
})
// kilocode_change start - create/reuse a git worktree before starting
.option("worktree", {
type: "string",
describe: "create (or reuse) a git worktree with this name and start kilo there",
})
// kilocode_change end
.option("prompt", {
type: "string",
describe: "prompt to use",
Expand All @@ -182,6 +188,7 @@ export const TuiThreadCommand = cmd({
const { importCloudSession, localSessionID, validateCloudFork } = await import("@/kilocode/cloud-session")
const { KiloTuiThreadDaemon } = await import("@/kilocode/cli/cmd/tui/thread")
const { preload } = await import("@/kilocode/cli/cmd/tui")
const { resolveTuiDirectory } = await import("@/kilocode/cli/cmd/tui-worktree")
// kilocode_change end
const unguard = win32InstallCtrlCGuard()
const shutdown = {
Expand All @@ -206,7 +213,14 @@ export const TuiThreadCommand = cmd({

// Resolve relative --project paths from PWD, then use the real cwd after
// chdir so the thread and worker share the same directory key.
const next = resolveThreadDirectory(args.project)
// kilocode_change start - `--worktree <name>` creates/reuses a worktree; resuming
// an explicit `--session <id>` tries to restart in that session's worktree
const next = await resolveTuiDirectory(args, resolveThreadDirectory(args.project)).catch((error) => {
UI.error(errorMessage(error))
process.exitCode = 1
})
if (!next) return
// kilocode_change end
const file = await target()
// kilocode_change start
const preloads = preload(typeof KILO_WORKER_PATH !== "undefined", () =>
Expand Down
129 changes: 129 additions & 0 deletions packages/opencode/src/kilocode/cli/cmd/tui-worktree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// kilocode_change - new file
// Supports `kilo --worktree <name>` (create/reuse a git worktree before the TUI
// starts) and resuming an explicit `--session <id>` in the worktree it was
// created in.
import path from "path"
import { Effect } from "effect"
import { UI } from "@/cli/ui"
import { Filesystem } from "@/util/filesystem"

function slugify(name: string) {
return name
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
}

async function withInstance<A>(root: string, fn: (run: <T>(effect: Effect.Effect<T, any, any>) => Promise<T>) => Promise<A>) {
Comment thread
brunoagatao marked this conversation as resolved.
Resolved
const { AppRuntime } = await import("@/effect/app-runtime")
const { InstanceStore } = await import("@/project/instance-store")
const { InstanceRef } = await import("@/effect/instance-ref")
const { store, ctx } = await AppRuntime.runPromise(
InstanceStore.Service.use((store) => store.load({ directory: root }).pipe(Effect.map((ctx) => ({ store, ctx })))),
)
const run = <T>(effect: Effect.Effect<T, any, any>) =>
AppRuntime.runPromise(effect.pipe(Effect.provideService(InstanceRef, ctx)))
try {
return await fn(run)
} finally {
await AppRuntime.runPromise(store.dispose(ctx))
}
}

type WaitResult = { ok: true } | { ok: false; message: string }

/** Waits for the `worktree.ready`/`worktree.failed` event for `directory`, with
* a `cancel()` handle so a caller can 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)
}
const timer = setTimeout(() => {
cleanup()
deferred.resolve({ ok: false, message: "Timed out waiting for the worktree to finish setting up" })
}, timeoutMs)
timer.unref?.()
Comment thread
brunoagatao marked this conversation as resolved.
Resolved
handler = (e) => {
if (e.directory !== directory) return
if (e.payload?.type === event.Ready.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 slug = slugify(name)
if (!slug) throw new Error(`Invalid worktree name "${name}"`)
return withInstance(root, async (run) => {
const existing = await run(Worktree.Service.use((svc) => svc.list()))
// list() remaps `name` to the project ID when a worktree's basename collides
// with the primary checkout's basename, so also match on the directory itself.
const found = existing.find(
(w) => w.name.toLowerCase() === slug || path.basename(w.directory).toLowerCase() === slug,
)
if (found && (await Filesystem.exists(found.directory))) {
Comment thread
brunoagatao marked this conversation as resolved.
Resolved
UI.println(`Using existing worktree "${found.name}" at ${found.directory}`)
return found.directory
}

const info = await run(Worktree.Service.use((svc) => svc.makeWorktreeInfo({ name })))
UI.println(`Creating worktree "${info.name}"...`)
const wait = waitForWorktreeEvent(GlobalBus, Worktree.Event, info.directory, timeoutMs)
await run(Worktree.Service.use((svc) => svc.createFromInfo(info))).catch((error) => {
wait.cancel()
throw error
})
const result = await wait.promise
if (!result.ok) throw new Error(`Failed to create worktree "${info.name}": ${result.message}`)
UI.println(`Worktree ready at ${info.directory}`)
Comment thread
brunoagatao marked this conversation as resolved.
Resolved
return info.directory
})
}

async function resolveSessionWorktree(sessionID: string, fallback: string) {
try {
const { AppRuntime } = await import("@/effect/app-runtime")
const { Session } = await import("@/session/session")
const { SessionID } = await import("@/session/schema")
const { Schema } = await import("effect")
const session = await AppRuntime.runPromise(
Comment thread
brunoagatao marked this conversation as resolved.
Resolved
Session.Service.use((svc) => svc.get(Schema.decodeUnknownSync(SessionID)(sessionID))),
)
if (!session.directory || session.directory === fallback) return fallback
if (!(await Filesystem.exists(session.directory))) return fallback
UI.println(`Resuming session in its original worktree: ${session.directory}`)
return session.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) {
Comment thread
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)
}
Loading