Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(worktree): executor-injected worktree ops + GitService wiring

enes18cb06b5b297
diff --git a/src/main/git-service.ts b/src/main/git-service.ts
index fb510fa88..f22db98b4 100644
--- a/src/main/git-service.ts
+++ b/src/main/git-service.ts
@@ -1,11 +1,13 @@
import { execFile, spawn } from 'child_process'
import fs from 'fs'
+import os from 'os'
import path from 'path'
import { promisify } from 'util'
import { ipcMain } from 'electron'
import { IPC } from '../shared/ipc'
import type { GitFileChange, GitResult, GitStatus } from '../shared/types'
import { loadGitHistoryFromExecutor } from '../shared/git-history'
+import * as worktreeOps from '@shared/worktree-ops'
import type { GitHistoryOptions, GitHistoryResult } from '../shared/git-history'
const run = promisify(execFile)
@@ -177,6 +179,33 @@ export class GitService {
ipcMain.handle(IPC.gitRemoteCommitUrl, (_e, cwd: string, sha: string) =>
this.remoteCommitUrl(cwd, sha)
)
+ ipcMain.handle(IPC.gitRepoRoot, (_e, cwd: string) => this.repoRoot(cwd))
+ ipcMain.handle(IPC.gitWorktreeList, (_e, repoPath: string) => this.worktreeList(repoPath))
+ ipcMain.handle(IPC.gitWorktreeAdd, (_e, repoPath: string, wtPath: string, branch: string, baseRef: string, isNew: boolean) =>
+ this.worktreeAdd(repoPath, wtPath, branch, baseRef, isNew)
+ )
+ ipcMain.handle(IPC.gitWorktreeMerge, (_e, repoPath: string, branch: string, baseRef: string) =>
+ this.worktreeMerge(repoPath, branch, baseRef)
+ )
+ ipcMain.handle(IPC.gitWorktreeRemove, (_e, repoPath: string, wtPath: string, deleteBranch: boolean) =>
+ this.worktreeRemove(repoPath, wtPath, deleteBranch)
+ )
+ }
+
+ repoRoot(cwd: string) {
+ return worktreeOps.repoRoot(git, cwd)
+ }
+ worktreeList(repoPath: string) {
+ return worktreeOps.worktreeList(git, repoPath)
+ }
+ worktreeAdd(repoPath: string, wtPath: string, branch: string, baseRef: string, isNew: boolean) {
+ return worktreeOps.worktreeAdd(git, repoPath, wtPath, branch, baseRef, isNew)
+ }
+ worktreeMerge(repoPath: string, branch: string, baseRef: string) {
+ return worktreeOps.worktreeMerge(git, repoPath, branch, baseRef)
+ }
+ worktreeRemove(repoPath: string, wtPath: string, deleteBranch: boolean) {
+ return worktreeOps.worktreeRemove(git, repoPath, wtPath, os.homedir(), deleteBranch)
}
async status(cwd: string): Promise<GitStatus> {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 1c016892d..193c28d2e 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -94,7 +94,15 @@ const api: NodeTerminalApi = {
generateMessage: (cwd) => ipcRenderer.invoke(IPC.commitGenerate, cwd),
history: (cwd, options) => ipcRenderer.invoke(IPC.gitHistory, cwd, options),
commitFiles: (cwd, oid) => ipcRenderer.invoke(IPC.gitCommitFiles, cwd, oid),
- remoteCommitUrl: (cwd, sha) => ipcRenderer.invoke(IPC.gitRemoteCommitUrl, cwd, sha)
+ remoteCommitUrl: (cwd, sha) => ipcRenderer.invoke(IPC.gitRemoteCommitUrl, cwd, sha),
+ repoRoot: (cwd) => ipcRenderer.invoke(IPC.gitRepoRoot, cwd),
+ worktreeList: (repoPath) => ipcRenderer.invoke(IPC.gitWorktreeList, repoPath),
+ worktreeAdd: (repoPath, wtPath, branch, baseRef, isNew) =>
+ ipcRenderer.invoke(IPC.gitWorktreeAdd, repoPath, wtPath, branch, baseRef, isNew),
+ worktreeMerge: (repoPath, branch, baseRef) =>
+ ipcRenderer.invoke(IPC.gitWorktreeMerge, repoPath, branch, baseRef),
+ worktreeRemove: (repoPath, wtPath, deleteBranch) =>
+ ipcRenderer.invoke(IPC.gitWorktreeRemove, repoPath, wtPath, deleteBranch)
},
clipboard: {
writeText: (text: string) => clipboard.writeText(text)
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 0606391cc..5e76f8835 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -76,6 +76,11 @@ export const IPC = {
gitHistory: 'git:history',
gitCommitFiles: 'git:commit-files',
gitRemoteCommitUrl: 'git:remote-commit-url',
+ gitRepoRoot: 'git:repo-root',
+ gitWorktreeList: 'git:worktree-list',
+ gitWorktreeAdd: 'git:worktree-add',
+ gitWorktreeMerge: 'git:worktree-merge',
+ gitWorktreeRemove: 'git:worktree-remove',
shellOpenExternal: 'shell:open-external',
commitGenerate: 'commit:generate',
remoteHostStart: 'remote:host:start',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f735ece02..a68fb9bda 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -339,6 +339,11 @@ export interface GitApi {
commitFiles(cwd: string, oid: string): Promise<GitFileChange[]>
/** Remote web URL for a commit sha, or null if it can't be derived. */
remoteCommitUrl(cwd: string, sha: string): Promise<string | null>
+ repoRoot(cwd: string): Promise<string | null>
+ worktreeList(repoPath: string): Promise<import('./worktree').WorktreeEntry[]>
+ worktreeAdd(repoPath: string, wtPath: string, branch: string, baseRef: string, isNew: boolean): Promise<GitResult>
+ worktreeMerge(repoPath: string, branch: string, baseRef: string): Promise<GitResult>
+ worktreeRemove(repoPath: string, wtPath: string, deleteBranch: boolean): Promise<GitResult>
}
export interface UpdateInfo {
diff --git a/src/shared/worktree-ops.test.ts b/src/shared/worktree-ops.test.ts
new file mode 100644
index 000000000..a7db8bb1e
--- /dev/null
+++ b/src/shared/worktree-ops.test.ts
@@ -0,0 +1,84 @@
+import { describe, it, expect } from 'vitest'
+import { worktreeAdd, worktreeMerge, worktreeRemove, type GitExec } from './worktree-ops'
+
+const ok = (out = ''): GitExec => ({ ok: true, out, err: '' })
+const ko = (err = 'fail'): GitExec => ({ ok: false, out: '', err })
+
+/** Fake git executor: returns a canned result keyed by `args.join(' ')`, records every call. */
+function fakeGit(handlers: Record<string, GitExec>) {
+ const calls: string[][] = []
+ const git = async (_cwd: string, args: string[]): Promise<GitExec> => {
+ calls.push(args)
+ return handlers[args.join(' ')] ?? ok()
+ }
+ return { git, calls }
+}
+
+describe('worktreeAdd', () => {
+ it('uses --no-track -b for a new branch', async () => {
+ const { git, calls } = fakeGit({})
+ const r = await worktreeAdd(git, '/repo', '/wt/x', 'feature/x', 'main', true)
+ expect(r.ok).toBe(true)
+ expect(calls[0]).toEqual(['worktree', 'add', '--no-track', '-b', 'feature/x', '/wt/x', 'main'])
+ })
+ it('rejects a flag-injecting branch name without calling git', async () => {
+ const { git, calls } = fakeGit({})
+ const r = await worktreeAdd(git, '/repo', '/wt/x', '--evil', 'main', true)
+ expect(r.ok).toBe(false)
+ expect(calls.length).toBe(0)
+ })
+})
+
+describe('worktreeMerge', () => {
+ it('fetch-updates when base is not checked out (no merge call)', async () => {
+ const list = 'worktree /wt/x\nHEAD aaa\nbranch refs/heads/feature/x\n'
+ const { git, calls } = fakeGit({ 'worktree list --porcelain': ok(list) })
+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main')
+ expect(r.ok).toBe(true)
+ expect(calls.some((c) => c[0] === 'fetch')).toBe(true)
+ expect(calls.some((c) => c[0] === 'merge')).toBe(false)
+ })
+ it('merges in place and aborts on conflict', async () => {
+ const list = 'worktree /repo\nHEAD aaa\nbranch refs/heads/main\n'
+ const { git, calls } = fakeGit({
+ 'worktree list --porcelain': ok(list),
+ 'status --porcelain': ok(''), // base clean
+ 'merge --no-ff --no-edit feature/x': ko('CONFLICT')
+ })
+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main')
+ expect(r.ok).toBe(false)
+ expect(calls.some((c) => c.join(' ') === 'merge --abort')).toBe(true)
+ })
+ it('blocks when the base checkout is dirty', async () => {
+ const list = 'worktree /repo\nHEAD aaa\nbranch refs/heads/main\n'
+ const { git } = fakeGit({
+ 'worktree list --porcelain': ok(list),
+ 'status --porcelain': ok(' M file.ts') // dirty
+ })
+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main')
+ expect(r.ok).toBe(false)
+ })
+})
+
+describe('worktreeRemove', () => {
+ it('refuses the repo path itself (no git call)', async () => {
+ const { git, calls } = fakeGit({})
+ const r = await worktreeRemove(git, '/repo', '/repo', '/home', true)
+ expect(r.ok).toBe(false)
+ expect(calls.length).toBe(0)
+ })
+ it('refuses an unregistered worktree path', async () => {
+ const { git } = fakeGit({ 'worktree list --porcelain': ok('worktree /repo\nbranch refs/heads/main\n') })
+ const r = await worktreeRemove(git, '/repo', '/wt/ghost', '/home', false)
+ expect(r.ok).toBe(false)
+ })
+ it('removes a registered worktree, prunes, and deletes the branch', async () => {
+ const list = 'worktree /repo\nbranch refs/heads/main\n\nworktree /wt/x\nbranch refs/heads/feature/x\n'
+ const { git, calls } = fakeGit({ 'worktree list --porcelain': ok(list) })
+ const r = await worktreeRemove(git, '/repo', '/wt/x', '/home', true)
+ expect(r.ok).toBe(true)
+ expect(calls.some((c) => c.join(' ') === 'worktree remove --force /wt/x')).toBe(true)
+ expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(true)
+ expect(calls.some((c) => c.join(' ') === 'branch -d feature/x')).toBe(true)
+ })
+})
diff --git a/src/shared/worktree-ops.ts b/src/shared/worktree-ops.ts
new file mode 100644
index 000000000..d8275c3e7
--- /dev/null
+++ b/src/shared/worktree-ops.ts
@@ -0,0 +1,92 @@
+import {
+ parseWorktreePorcelain,
+ isDangerousWorktreeRemovalPath,
+ decideMergeStrategy,
+ isValidGitRef,
+ type WorktreeEntry
+} from './worktree'
+
+/** One git invocation's result (mirrors git-service.ts's internal `Exec`). */
+export interface GitExec { ok: boolean; out: string; err: string }
+/** Injected git runner: runs `git <args>` in `cwd`. */
+export type GitExecutor = (cwd: string, args: string[]) => Promise<GitExec>
+/** Renderer-facing result (structurally a `GitResult`). */
+export interface WorktreeOpResult { ok: boolean; message: string }
+
+export async function repoRoot(git: GitExecutor, cwd: string): Promise<string | null> {
+ if (!cwd) return null
+ const r = await git(cwd, ['rev-parse', '--show-toplevel'])
+ return r.ok ? r.out.trim() : null
+}
+
+export async function worktreeList(git: GitExecutor, repoPath: string): Promise<WorktreeEntry[]> {
+ if (!repoPath) return []
+ const r = await git(repoPath, ['worktree', 'list', '--porcelain'])
+ return r.ok ? parseWorktreePorcelain(r.out) : []
+}
+
+export async function worktreeAdd(
+ git: GitExecutor, repoPath: string, wtPath: string, branch: string, baseRef: string, isNew: boolean
+): Promise<WorktreeOpResult> {
+ if (!repoPath || !wtPath) return { ok: false, message: 'Missing repo or worktree path.' }
+ if (!isValidGitRef(branch)) return { ok: false, message: 'Invalid branch name.' }
+ if (isNew && !isValidGitRef(baseRef)) return { ok: false, message: 'Invalid base ref.' }
+ // `--no-track` so a new branch does not inherit upstream and report "behind".
+ const args = isNew
+ ? ['worktree', 'add', '--no-track', '-b', branch, wtPath, baseRef]
+ : ['worktree', 'add', wtPath, branch]
+ const r = await git(repoPath, args)
+ return r.ok ? { ok: true, message: `Worktree ready at ${wtPath}.` } : { ok: false, message: r.err }
+}
+
+export async function worktreeMerge(
+ git: GitExecutor, repoPath: string, branch: string, baseRef: string
+): Promise<WorktreeOpResult> {
+ if (!isValidGitRef(branch) || !isValidGitRef(baseRef)) return { ok: false, message: 'Invalid ref.' }
+ const list = await worktreeList(git, repoPath)
+ const baseEntry = list.find((e) => e.branch === baseRef) ?? null
+ let baseDirty = false
+ if (baseEntry) {
+ const st = await git(baseEntry.path, ['status', '--porcelain'])
+ baseDirty = st.ok && st.out.trim().length > 0
+ }
+ const plan = decideMergeStrategy({ baseCheckedOutPath: baseEntry?.path ?? null, baseDirty })
+ if (plan.kind === 'blocked') return { ok: false, message: plan.reason }
+
+ if (plan.kind === 'fetch-update') {
+ // Base not checked out anywhere → advance the ref without touching a working tree.
+ const r = await git(repoPath, ['fetch', '.', `${branch}:${baseRef}`])
+ if (!r.ok) return { ok: false, message: `Cannot fast-forward ${baseRef}. Merge manually in a terminal.` }
+ } else {
+ // Base is checked out and clean → merge in that checkout.
+ const r = await git(plan.path, ['merge', '--no-ff', '--no-edit', branch])
+ if (!r.ok) {
+ await git(plan.path, ['merge', '--abort'])
+ return { ok: false, message: 'Merge conflict. Resolve it in the worktree terminal.' }
+ }
+ }
+ // Best-effort push if a remote exists; ignore failure (offline / no remote).
+ const hasRemote = (await git(repoPath, ['remote'])).out.trim().length > 0
+ if (hasRemote) await git(repoPath, ['push', 'origin', baseRef])
+ return { ok: true, message: `Merged ${branch} into ${baseRef}.` }
+}
+
+export async function worktreeRemove(
+ git: GitExecutor, repoPath: string, wtPath: string, homeDir: string, deleteBranch: boolean
+): Promise<WorktreeOpResult> {
+ if (isDangerousWorktreeRemovalPath(wtPath, repoPath, homeDir)) {
+ return { ok: false, message: 'Refusing to remove that path.' }
+ }
+ const list = await worktreeList(git, repoPath)
+ const entry = list.find((e) => e.path.replace(/\/+$/, '') === wtPath.replace(/\/+$/, ''))
+ if (!entry) return { ok: false, message: 'Worktree is not registered.' }
+ const branch = entry.branch
+ const rm = await git(repoPath, ['worktree', 'remove', '--force', wtPath])
+ if (!rm.ok) return { ok: false, message: rm.err }
+ await git(repoPath, ['worktree', 'prune'])
+ if (deleteBranch && branch && isValidGitRef(branch)) {
+ // -d refuses unmerged; the renderer decides whether to escalate to -D.
+ await git(repoPath, ['branch', '-d', branch])
+ }
+ return { ok: true, message: 'Worktree removed.' }
+}