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.

fix(worktree): a merge only pushes to origin when the user was told it would

enes640b417c0fc1
diff --git a/src/core/git-service.ts b/src/core/git-service.ts
index f774a26fd..d42d3c3c1 100644
--- a/src/core/git-service.ts
+++ b/src/core/git-service.ts
@@ -219,8 +219,8 @@ export class GitService {
platform().handle(IPC.gitWorktreeAdd, (repoPath: string, wtPath: string, branch: string, baseRef: string, isNew: boolean) =>
this.worktreeAdd(repoPath, wtPath, branch, baseRef, isNew)
)
- platform().handle(IPC.gitWorktreeMerge, (repoPath: string, branch: string, baseRef: string) =>
- this.worktreeMerge(repoPath, branch, baseRef)
+ platform().handle(IPC.gitWorktreeMerge, (repoPath: string, branch: string, baseRef: string, push?: boolean) =>
+ this.worktreeMerge(repoPath, branch, baseRef, push)
)
platform().handle(IPC.gitWorktreeRemove, (repoPath: string, wtPath: string, deleteBranch: boolean, pruneOnly?: boolean) =>
this.worktreeRemove(repoPath, wtPath, deleteBranch, pruneOnly)
@@ -236,11 +236,14 @@ export class GitService {
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)
+ worktreeMerge(repoPath: string, branch: string, baseRef: string, push = false) {
+ return worktreeOps.worktreeMerge(git, repoPath, branch, baseRef, push)
}
worktreeRemove(repoPath: string, wtPath: string, deleteBranch: boolean, pruneOnly = false) {
- return worktreeOps.worktreeRemove(git, repoPath, wtPath, os.homedir(), deleteBranch, pruneOnly)
+ // `pathExists` is git's `prunable` flag's fallback for git < 2.36 (see worktree-ops).
+ return worktreeOps.worktreeRemove(git, repoPath, wtPath, os.homedir(), deleteBranch, pruneOnly, async (p) =>
+ fs.existsSync(p)
+ )
}
async status(cwd: string): Promise<GitStatus> {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 729e72b9f..f1b3b2408 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -168,8 +168,8 @@ const api: NodeTerminalApi = {
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),
+ worktreeMerge: (repoPath, branch, baseRef, push) =>
+ ipcRenderer.invoke(IPC.gitWorktreeMerge, repoPath, branch, baseRef, push),
worktreeRemove: (repoPath, wtPath, deleteBranch, pruneOnly) =>
ipcRenderer.invoke(IPC.gitWorktreeRemove, repoPath, wtPath, deleteBranch, pruneOnly),
setActiveRemote: (projectId) => ipcRenderer.invoke(IPC.gitSetActiveRemote, projectId)
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 7ebff6225..b9f48b356 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -294,12 +294,13 @@ export function buildFilesApi(
baseRef,
isNew
) as ReturnType<GitApi['worktreeAdd']>,
- worktreeMerge: (repoPath, branch, baseRef) =>
+ worktreeMerge: (repoPath, branch, baseRef, push) =>
client.request(
IPC.gitWorktreeMerge,
repoPath,
branch,
- baseRef
+ baseRef,
+ push
) as ReturnType<GitApi['worktreeMerge']>,
worktreeRemove: (repoPath, wtPath, deleteBranch, pruneOnly) =>
client.request(
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index c0b82c537..7b286be81 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -444,6 +444,17 @@ export function Canvas() {
canDelete: boolean
} | null>(null)
const [deleteFromDisk, setDeleteFromDisk] = useState(false)
+ // Group awaiting confirmation to merge its worktree into the base branch. `hasRemote` decides
+ // whether the dialog offers (and warns about) the push to origin — a repo with no remote must
+ // never be threatened with a publish that cannot happen.
+ const [mergeTarget, setMergeTarget] = useState<{
+ groupId: string
+ repoPath: string
+ branch: string
+ baseRef: string
+ hasRemote: boolean
+ } | null>(null)
+ const [mergePush, setMergePush] = useState(false)
const settings = useSettings((s) => s.settings)
const viewportRef = useRef<Viewport>({ x: 0, y: 0, zoom: 1 })
const nodesRef = useRef<CanvasNode[]>(nodes)
@@ -2154,6 +2165,18 @@ export function Canvas() {
setNotice({ kind: res.ok ? 'info' : 'error', text: res.message })
}, [removeTarget, deleteFromDisk, clearWorktreeBinding])
+ // Confirmed merge. The push is passed explicitly: `worktreeMerge` never publishes on its own, so
+ // what the dialog said is exactly what runs — and the result banner names the push either way.
+ const confirmMergeWorktree = useCallback(() => {
+ const t = mergeTarget
+ setMergeTarget(null)
+ if (!t) return
+ const push = t.hasRemote && mergePush
+ void window.nodeTerminal.git
+ .worktreeMerge(t.repoPath, t.branch, t.baseRef, push)
+ .then((res) => setNotice({ kind: res.ok ? 'info' : 'error', text: res.message }))
+ }, [mergeTarget, mergePush])
+
// Worktree action dispatcher for GroupNode's header chip. Structured as a switch so the
// merge / remove teardown actions (Tasks 8 & 9) slot in as new cases. `unbind` forgets the
// binding without touching disk; `merge` merges to base; `remove` opens the safety dialog.
@@ -2180,19 +2203,20 @@ export function Canvas() {
if (!wt) return
// NEVER merge on a single click of a small header button: `worktreeMerge` merges into the
// base checkout when that base is checked out somewhere — i.e. straight into the user's
- // main working tree. Ask first, and say so.
- setConfirm({
- message:
- `Merge ${wt.branch} into ${wt.baseRef}?\n\n` +
- `If ${wt.baseRef} is checked out somewhere, this merges into that working tree.`,
- confirmLabel: 'Merge',
- danger: false,
- onConfirm: () => {
- setConfirm(null)
- void window.nodeTerminal.git
- .worktreeMerge(wt.repoPath, wt.branch, wt.baseRef)
- .then((res) => setNotice({ kind: res.ok ? 'info' : 'error', text: res.message }))
- }
+ // main working tree — AND (if asked) pushes the base branch to origin, which publishes it
+ // to every teammate. Ask first, and say BOTH of those out loud.
+ //
+ // `hasRemote` comes from the store's status poll (the chip that carries this very button
+ // has been polling it), so no extra git IPC is fired here. Unknown → assume no remote:
+ // the merge then does not push, which is the only safe way to be wrong.
+ const hasRemote = !!useWorktrees.getState().statusByPath[wt.path]?.hasRemote
+ setMergePush(hasRemote) // pushing is the default when a remote exists — but opt-out.
+ setMergeTarget({
+ groupId,
+ repoPath: wt.repoPath,
+ branch: wt.branch,
+ baseRef: wt.baseRef,
+ hasRemote
})
break
}
@@ -4492,6 +4516,34 @@ export function Canvas() {
/>
)}
+ {mergeTarget && (
+ <ConfirmDialog
+ message={
+ `Merge ${mergeTarget.branch} into ${mergeTarget.baseRef}?\n\n` +
+ `If ${mergeTarget.baseRef} is checked out somewhere, this merges into that working tree.` +
+ (mergeTarget.hasRemote && mergePush
+ ? `\n\n⚠ ${mergeTarget.baseRef} is also pushed to origin — everyone on the remote gets this merge.`
+ : '')
+ }
+ confirmLabel="Merge"
+ danger={false}
+ option={
+ // No remote → no push to offer. With a remote, the push stays the default (it is what
+ // the user almost always wants after merging a finished worktree) but is now visible
+ // and switch-offable, instead of happening silently behind a dialog that never said so.
+ mergeTarget.hasRemote
+ ? {
+ label: `Also push ${mergeTarget.baseRef} to origin`,
+ checked: mergePush,
+ onChange: setMergePush
+ }
+ : undefined
+ }
+ onConfirm={confirmMergeWorktree}
+ onCancel={() => setMergeTarget(null)}
+ />
+ )}
+
{removeTarget && (
<ConfirmDialog
message={
diff --git a/src/renderer/state/worktrees.test.ts b/src/renderer/state/worktrees.test.ts
index b9e77c020..901ceadbd 100644
--- a/src/renderer/state/worktrees.test.ts
+++ b/src/renderer/state/worktrees.test.ts
@@ -141,7 +141,8 @@ describe('useWorktrees.refreshStatus', () => {
branch: 'feat',
dirty: 3,
ahead: 3,
- behind: 1
+ behind: 1,
+ hasRemote: false
})
})
@@ -188,24 +189,65 @@ describe('useWorktrees.refreshStatus', () => {
// `refresh()` only runs on project load / mutation, so without this the chip of a worktree
// deleted WHILE THE USER WATCHES would keep claiming to be healthy until a reload.
- it('marks the group stale when its worktree stops being a repo', async () => {
+ it('marks the group stale when its worktree stops being a repo (after a second read agrees)', async () => {
+ const t0 = 1_700_000_000_000
+ vi.useFakeTimers()
+ vi.setSystemTime(t0)
gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
+ await useWorktrees.getState().refreshStatus('/wt/gone', 'group-1')
+ vi.setSystemTime(t0 + WORKTREE_STATUS_THROTTLE_MS + 1)
await useWorktrees.getState().refreshStatus('/wt/gone', 'group-1')
expect(useWorktrees.getState().staleGroupIds).toEqual(['group-1'])
})
+ // `git rev-parse --is-inside-work-tree` merely FAILING (spawn EAGAIN under load, an NFS/FUSE
+ // hiccup) also answers hasRepo:false. Flipping a healthy worktree to "missing" on one such read
+ // is not cosmetic: while it lasts, cwdForNewNodeIn hands out the project cwd instead of the
+ // worktree path, and a terminal created in that window persists the WRONG cwd forever.
+ it('does not flip a healthy worktree to stale on a single hasRepo:false read', async () => {
+ const t0 = 1_700_000_000_000
+ vi.useFakeTimers()
+ vi.setSystemTime(t0)
+ gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
+
+ await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')
+
+ expect(useWorktrees.getState().staleGroupIds).toEqual([])
+ })
+
+ it('forgets the miss when the next read succeeds (a transient failure never accumulates)', async () => {
+ const t0 = 1_700_000_000_000
+ vi.useFakeTimers()
+ vi.setSystemTime(t0)
+ gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
+ await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')
+
+ vi.setSystemTime(t0 + WORKTREE_STATUS_THROTTLE_MS + 1)
+ gitMock.status.mockResolvedValue(okStatus())
+ await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')
+ expect(useWorktrees.getState().staleGroupIds).toEqual([])
+
+ // A LATER isolated miss must start counting from scratch, not tip the group over.
+ vi.setSystemTime(t0 + 2 * WORKTREE_STATUS_THROTTLE_MS + 2)
+ gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
+ await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')
+ expect(useWorktrees.getState().staleGroupIds).toEqual([])
+ })
+
it('un-marks a stale group once its worktree answers again', async () => {
const t0 = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(t0)
gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')
+ vi.setSystemTime(t0 + WORKTREE_STATUS_THROTTLE_MS + 1)
+ await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')
expect(useWorktrees.getState().staleGroupIds).toEqual(['group-1'])
- // Restored (or the previous read failed transiently) — past the throttle window.
- vi.setSystemTime(t0 + WORKTREE_STATUS_THROTTLE_MS + 1)
+ // Restored — past the throttle window.
+ vi.setSystemTime(t0 + 2 * WORKTREE_STATUS_THROTTLE_MS + 2)
gitMock.status.mockResolvedValue(okStatus())
await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')
@@ -213,6 +255,16 @@ describe('useWorktrees.refreshStatus', () => {
expect(useWorktrees.getState().statusByPath['/wt/feat'].branch).toBe('feat')
})
+ // The merge confirm has to tell the user whether merging also PUBLISHES to origin, and it reads
+ // that fact from here (the store is the only caller of the status IPC).
+ it('carries hasRemote into the chip status (the merge confirm reads it)', async () => {
+ gitMock.status.mockResolvedValue(okStatus({ hasRemote: true }))
+
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+
+ expect(useWorktrees.getState().statusByPath['/wt/feat'].hasRemote).toBe(true)
+ })
+
it('leaves staleness alone when no group id is given', async () => {
gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
@@ -235,7 +287,8 @@ describe('useWorktrees.refreshStatus', () => {
branch: 'feat',
dirty: 0,
ahead: 2,
- behind: 0
+ behind: 0,
+ hasRemote: false
})
})
diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.ts
index c32b2bf7e..62981a2e2 100644
--- a/src/renderer/state/worktrees.ts
+++ b/src/renderer/state/worktrees.ts
@@ -12,11 +12,25 @@ export interface WorktreeStatus {
dirty: number
ahead: number
behind: number
+ /** The repo has a remote — i.e. a merge CAN publish the base branch to origin. The merge confirm
+ * reads this to say so (and to not threaten a push that could never happen). */
+ hasRemote: boolean
}
/** The chip re-renders constantly; without this, every render would spawn a `git status`. */
export const WORKTREE_STATUS_THROTTLE_MS = 4000
+/**
+ * How many CONSECUTIVE "this is not a repo" reads it takes to declare a bound worktree missing.
+ *
+ * `git.status()` answers `hasRepo:false` whenever `git rev-parse --is-inside-work-tree` merely
+ * FAILS — a spawn EAGAIN under load, an NFS/FUSE hiccup — not only when the directory is gone. One
+ * such read used to flip a perfectly healthy group to "missing"; it self-heals on the next poll,
+ * but in that window `cwdForNewNodeIn` refuses the worktree path and hands out the project cwd, and
+ * a terminal created then persists the WRONG cwd forever. Two reads in a row is the stronger signal.
+ */
+export const WORKTREE_STALE_STRIKES = 2
+
interface WorktreesState {
repoRoot: string | null
entries: WorktreeEntry[]
@@ -36,6 +50,8 @@ interface WorktreesState {
}
const lastStatusAt = new Map<string, number>()
+/** Consecutive `hasRepo:false` reads per path (see WORKTREE_STALE_STRIKES). Reset by any success. */
+const missStreak = new Map<string, number>()
/**
* Cancellation token for the in-flight async reads. `refresh`/`refreshStatus` are fired from React
@@ -114,9 +130,13 @@ export const useWorktrees = create<WorktreesState>((set) => ({
if (mineEpoch !== epoch) return
// A deleted worktree does NOT reject: git-service answers with an empty status. Writing it
// would render a dead worktree as a healthy one on a blank branch — `staleGroupIds` is what
- // tells that story, so mark the group stale instead of keeping a lie on screen.
+ // tells that story, so mark the group stale instead of keeping a lie on screen. But only once
+ // the reading REPEATS: a single failed read is as likely to be a transient git failure as a
+ // deleted directory, and calling a live worktree missing has consequences of its own.
if (!status.hasRepo) {
- if (groupId) {
+ const strikes = (missStreak.get(path) ?? 0) + 1
+ missStreak.set(path, strikes)
+ if (groupId && strikes >= WORKTREE_STALE_STRIKES) {
set((s) =>
s.staleGroupIds.includes(groupId)
? s
@@ -125,6 +145,7 @@ export const useWorktrees = create<WorktreesState>((set) => ({
}
return
}
+ missStreak.delete(path)
set((s) => ({
// The directory answers again (restored, or a transient read failure passed) → not stale.
staleGroupIds:
@@ -137,7 +158,8 @@ export const useWorktrees = create<WorktreesState>((set) => ({
branch: status.branch,
dirty: status.staged.length + status.changes.length,
ahead: status.ahead,
- behind: status.behind
+ behind: status.behind,
+ hasRemote: !!status.hasRemote
}
}
}))
@@ -146,6 +168,7 @@ export const useWorktrees = create<WorktreesState>((set) => ({
reset() {
epoch++
lastStatusAt.clear()
+ missStreak.clear()
set({ ...empty(), statusByPath: {} })
}
}))
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 4c49d97d1..1e1b5463c 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -607,7 +607,9 @@ export interface GitApi {
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>
+ /** `push`: also publish `baseRef` to origin after a successful merge (only if a remote exists).
+ * Opt-in — a merge must never publish to a shared remote the user was not told about. */
+ worktreeMerge(repoPath: string, branch: string, baseRef: string, push?: boolean): Promise<GitResult>
/** `pruneOnly`: clean up git's registration only — never delete a directory. Used to prune a
* stale binding whose worktree was already deleted outside the app. */
worktreeRemove(repoPath: string, wtPath: string, deleteBranch: boolean, pruneOnly?: boolean): Promise<GitResult>
diff --git a/src/shared/worktree-ops.test.ts b/src/shared/worktree-ops.test.ts
index eb5455c9f..11e23a2a2 100644
--- a/src/shared/worktree-ops.test.ts
+++ b/src/shared/worktree-ops.test.ts
@@ -83,6 +83,57 @@ describe('worktreeMerge', () => {
expect(r.message).toContain('/base')
expect(r.message).not.toContain('worktree terminal')
})
+
+ // The push is what the user is asked to consent to (Task 6): merging must NEVER publish to a
+ // shared remote unless the caller explicitly said so.
+ it('never pushes unless the caller asks for it', async () => {
+ const list = 'worktree /wt/x\nHEAD aaa\nbranch refs/heads/feature/x\n'
+ const { git, calls } = fakeGit({ 'worktree list --porcelain': ok(list), remote: ok('origin\n') })
+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main')
+ expect(r.ok).toBe(true)
+ expect(calls.some((c) => c[0] === 'push')).toBe(false)
+ expect(r.message).not.toMatch(/push/i)
+ })
+ it('pushes the base branch to origin when asked, and says so', async () => {
+ const list = 'worktree /wt/x\nHEAD aaa\nbranch refs/heads/feature/x\n'
+ const { git, calls } = fakeGit({ 'worktree list --porcelain': ok(list), remote: ok('origin\n') })
+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main', true)
+ expect(r.ok).toBe(true)
+ expect(calls.some((c) => c.join(' ') === 'push origin main')).toBe(true)
+ expect(r.message).toMatch(/pushed main to origin/i)
+ })
+ it('does not push when the repo has no remote (and does not claim it did)', async () => {
+ const list = 'worktree /wt/x\nHEAD aaa\nbranch refs/heads/feature/x\n'
+ const { git, calls } = fakeGit({ 'worktree list --porcelain': ok(list), remote: ok('') })
+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main', true)
+ expect(r.ok).toBe(true)
+ expect(calls.some((c) => c[0] === 'push')).toBe(false)
+ expect(r.message).not.toMatch(/push/i)
+ })
+ it('reports a failed push instead of swallowing it', async () => {
+ const list = 'worktree /wt/x\nHEAD aaa\nbranch refs/heads/feature/x\n'
+ const { git } = fakeGit({
+ 'worktree list --porcelain': ok(list),
+ remote: ok('origin\n'),
+ 'push origin main': ko('rejected')
+ })
+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main', true)
+ // The merge itself succeeded — only the publish failed, and the user must be told.
+ expect(r.ok).toBe(true)
+ expect(r.message).toMatch(/push.*failed/i)
+ })
+ it('does not merge again when only the push is requested — a failed merge never pushes', async () => {
+ const list = 'worktree /base\nHEAD aaa\nbranch refs/heads/main\n'
+ const { git, calls } = fakeGit({
+ 'worktree list --porcelain': ok(list),
+ 'status --porcelain': ok(''),
+ 'merge --no-ff --no-edit feature/x': ko('CONFLICT'),
+ remote: ok('origin\n')
+ })
+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main', true)
+ expect(r.ok).toBe(false)
+ expect(calls.some((c) => c[0] === 'push')).toBe(false)
+ })
})
describe('worktreeRemove', () => {
@@ -148,4 +199,30 @@ describe('worktreeRemove', () => {
expect(calls.some((c) => c[0] === 'branch')).toBe(false)
expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(false)
})
+ it('prunes an unregistered path even in pruneOnly mode (pruning IS the mode)', async () => {
+ const { git, calls } = fakeGit({
+ 'worktree list --porcelain': ok('worktree /repo\nbranch refs/heads/main\n')
+ })
+ const r = await worktreeRemove(git, '/repo', '/wt/ghost', '/home', false, true)
+ expect(r.worktreeGone).toBe(true)
+ expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(true)
+ })
+ // git < 2.36 does not emit `prunable` in `worktree list --porcelain`, so a deleted directory
+ // looks perfectly healthy in the listing. Stat the path instead of believing the flag.
+ it('treats a missing directory as gone even when git never flagged it prunable', 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', false, true, async () => false)
+ expect(r.ok).toBe(true)
+ expect(r.worktreeGone).toBe(true)
+ expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(true)
+ expect(calls.some((c) => c[1] === 'remove')).toBe(false)
+ })
+ it('still refuses to prune a directory that exists (a wrongly-stale group cannot delete it)', 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', false, true, async () => true)
+ expect(r.ok).toBe(false)
+ expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(false)
+ })
})
diff --git a/src/shared/worktree-ops.ts b/src/shared/worktree-ops.ts
index f39dc6f9d..153690924 100644
--- a/src/shared/worktree-ops.ts
+++ b/src/shared/worktree-ops.ts
@@ -52,8 +52,17 @@ export async function worktreeAdd(
return r.ok ? { ok: true, message: `Worktree ready at ${wtPath}.` } : { ok: false, message: r.err }
}
+/**
+ * Merge `branch` into `baseRef`, and — only when `push` is true AND the repo has a remote — publish
+ * the base branch to origin.
+ *
+ * The push is OPT-IN by design. It used to run "best effort" on every merge: one click on a small
+ * header chip published to `origin/main` (CI, teammates, protected-branch noise) without the confirm
+ * dialog ever mentioning it. Nothing here may do more than the caller disclosed to the user, so the
+ * default is not to push, and the result message states exactly what happened.
+ */
export async function worktreeMerge(
- git: GitExecutor, repoPath: string, branch: string, baseRef: string
+ git: GitExecutor, repoPath: string, branch: string, baseRef: string, push = false
): Promise<WorktreeOpResult> {
if (!isValidGitRef(branch) || !isValidGitRef(baseRef)) return { ok: false, message: 'Invalid ref.' }
const list = await worktreeList(git, repoPath)
@@ -83,10 +92,17 @@ export async function worktreeMerge(
}
}
}
- // Best-effort push if a remote exists; ignore failure (offline / no remote).
+ const merged = `Merged ${branch} into ${baseRef}.`
+ if (!push) return { ok: true, message: merged }
+ // Only push if a remote actually exists — never claim (or attempt) a publish that cannot happen.
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}.` }
+ if (!hasRemote) return { ok: true, message: merged }
+ const p = await git(repoPath, ['push', 'origin', baseRef])
+ // A failed push does not undo the merge, so this stays `ok` — but it is reported, not swallowed:
+ // the user must know whether origin has the merge.
+ return p.ok
+ ? { ok: true, message: `Merged ${branch} into ${baseRef} and pushed ${baseRef} to origin.` }
+ : { ok: true, message: `${merged} The push to origin failed — push ${baseRef} manually.` }
}
/**
@@ -100,7 +116,15 @@ export async function worktreeMerge(
*/
export async function worktreeRemove(
git: GitExecutor, repoPath: string, wtPath: string, homeDir: string, deleteBranch: boolean,
- pruneOnly = false
+ pruneOnly = false,
+ /**
+ * Does this path exist on disk? Injected (the shared layer has no fs). It is the fallback for
+ * git's `prunable` flag, which only exists from git 2.36: on an older git a deleted worktree is
+ * listed as perfectly healthy, so `prunable` alone would leave stale bindings unrecoverable and
+ * answer the user with a flatly untrue "the worktree directory still exists".
+ * Defaults to "it exists" — the conservative answer, which never deletes anything.
+ */
+ pathExists: (p: string) => Promise<boolean> = async () => true
): Promise<WorktreeOpResult> {
// Reject a path that could be parsed as an option flag (argv injection).
if (!wtPath || wtPath.startsWith('-')) return { ok: false, message: 'Invalid worktree path.' }
@@ -113,13 +137,18 @@ export async function worktreeRemove(
// Nothing to remove: git does not know this path (deleted + already pruned, or never a
// worktree of this repo). Prune anyway — a leftover registration elsewhere would block a
// future `worktree add` — and tell the caller the worktree is gone so it clears its binding.
- if (!pruneOnly) await git(repoPath, ['worktree', 'prune'])
+ // (Unconditionally: pruning is the whole point of `pruneOnly`, so skipping it there was
+ // exactly backwards.)
+ await git(repoPath, ['worktree', 'prune'])
return { ok: false, worktreeGone: true, message: 'Worktree is not registered — it is already gone.' }
}
const branch = entry.branch
- if (entry.prunable) {
- // git still lists it, but the directory is gone. `worktree remove` would fail; prune the
- // registration instead and touch no files.
+ // git still lists it, but is the directory actually there? `prunable` is git's own answer
+ // (≥ 2.36); the stat is the fallback for older gits, which never set the flag.
+ const dirGone = entry.prunable || !(await pathExists(wtPath))
+ if (dirGone) {
+ // The directory is gone. `worktree remove` would fail; prune the registration instead and
+ // touch no files.
await git(repoPath, ['worktree', 'prune'])
if (!pruneOnly && deleteBranch && branch && isValidGitRef(branch)) {
await git(repoPath, ['branch', '-d', branch])