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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(worktree): a deleted worktree is stale on every git, and a refresh never un-stales it
enes8739b7f740a6
diff --git a/src/core/git-service.ts b/src/core/git-service.tsindex d42d3c3c1..b3127cec2 100644--- a/src/core/git-service.ts+++ b/src/core/git-service.ts@@ -231,7 +231,10 @@ export class GitService {return worktreeOps.repoRoot(git, cwd)}worktreeList(repoPath: string) {- return worktreeOps.worktreeList(git, repoPath)+ // `pathExists` is git's `prunable` flag's fallback for git < 2.36 (see worktree-ops): without+ // it, an old git reports a deleted worktree directory as healthy and every consumer of+ // `prunable` (staleness, orphan adoption) believes it.+ return worktreeOps.worktreeList(git, repoPath, async (p) => fs.existsSync(p))}worktreeAdd(repoPath: string, wtPath: string, branch: string, baseRef: string, isNew: boolean) {return worktreeOps.worktreeAdd(git, repoPath, wtPath, branch, baseRef, isNew)diff --git a/src/renderer/state/worktrees.test.ts b/src/renderer/state/worktrees.test.tsindex 901ceadbd..ece1e130c 100644--- a/src/renderer/state/worktrees.test.ts+++ b/src/renderer/state/worktrees.test.ts@@ -265,6 +265,86 @@ describe('useWorktrees.refreshStatus', () => {expect(useWorktrees.getState().statusByPath['/wt/feat'].hasRemote).toBe(true)})++ // `refresh()` runs on a project switch, on binding another worktree, on deleting a node, on+ // ungrouping. If it SET `staleGroupIds` from reconcile alone, every one of those would erase a+ // group the poll had already proven dead — the chip goes healthy again and "↪ Move into worktree"+ // reopens the window in which it destroys a live session into a directory that no longer exists.+ it('a refresh does not erase staleness the strike counter established', 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 still lists the worktree as perfectly healthy (an old git that cannot say `prunable`, or+ // simply a `worktree list` that has not been re-read since). Reconcile therefore calls it live.+ gitMock.repoRoot.mockResolvedValue('/repo')+ gitMock.worktreeList.mockResolvedValue([+ { path: '/repo', branch: 'main', head: 'a', isBare: false },+ { path: '/wt/gone', branch: 'feat', head: 'b', isBare: false }+ ])+ await useWorktrees.getState().refresh('/repo', [+ { groupId: 'group-1', worktree: { path: '/wt/gone', repoPath: '/repo' } as never }+ ])++ expect(useWorktrees.getState().staleGroupIds).toEqual(['group-1'])+ })++ it('a refresh adds git´s own stale verdict to the struck-out ones (union, no duplicates)', 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')++ gitMock.repoRoot.mockResolvedValue('/repo')+ // git prunes /wt/gone away entirely (reconcile: stale) and marks /wt/dead prunable.+ gitMock.worktreeList.mockResolvedValue([+ { path: '/repo', branch: 'main', head: 'a', isBare: false },+ { path: '/wt/dead', branch: 'dead', head: 'c', isBare: false, prunable: true }+ ])+ await useWorktrees.getState().refresh('/repo', [+ { groupId: 'group-1', worktree: { path: '/wt/gone', repoPath: '/repo' } as never },+ { groupId: 'group-2', worktree: { path: '/wt/dead', repoPath: '/repo' } as never }+ ])++ expect([...useWorktrees.getState().staleGroupIds].sort()).toEqual(['group-1', 'group-2'])+ })++ it('a restored worktree is no longer stale after a refresh (the streak is cleared, not sticky)', 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'])++ // The directory answers again → the streak is forgotten, so the next refresh must not resurrect+ // the staleness out of the strike map.+ vi.setSystemTime(t0 + 2 * WORKTREE_STATUS_THROTTLE_MS + 2)+ gitMock.status.mockResolvedValue(okStatus())+ await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')++ gitMock.repoRoot.mockResolvedValue('/repo')+ gitMock.worktreeList.mockResolvedValue([+ { path: '/repo', branch: 'main', head: 'a', isBare: false },+ { path: '/wt/feat', branch: 'feat', head: 'b', isBare: false }+ ])+ await useWorktrees.getState().refresh('/repo', [+ { groupId: 'group-1', worktree: { path: '/wt/feat', repoPath: '/repo' } as never }+ ])++ expect(useWorktrees.getState().staleGroupIds).toEqual([])+ })+it('leaves staleness alone when no group id is given', async () => {gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.tsindex 62981a2e2..f7c6bbc65 100644--- a/src/renderer/state/worktrees.ts+++ b/src/renderer/state/worktrees.ts@@ -50,9 +50,16 @@ interface WorktreesState {}const lastStatusAt = new Map<string, number>()-/** Consecutive `hasRepo:false` reads per path (see WORKTREE_STALE_STRIKES). Reset by any success. */+/**+ * Consecutive `hasRepo:false` reads per worktree path (see WORKTREE_STALE_STRIKES). Reset by any+ * success. Keyed by the NORMALIZED path so `refresh` can look a binding up in it.+ */const missStreak = new Map<string, number>()+/** Has this path been read as "not a repo" often enough in a row to count as gone? */+const struckOut = (p: string): boolean =>+ (missStreak.get(normWorktreePath(p)) ?? 0) >= WORKTREE_STALE_STRIKES+/*** Cancellation token for the in-flight async reads. `refresh`/`refreshStatus` are fired from React* effects and have no abort; a project switch calls `reset()` and starts the NEW project's refresh,@@ -103,7 +110,15 @@ export const useWorktrees = create<WorktreesState>((set) => ({(b) => normWorktreePath(b.worktree.repoPath) === normWorktreePath(root))const { stale, orphans } = reconcileWorktrees(mine, entries)- set({ repoRoot: root, entries, orphans, staleGroupIds: stale })+ // UNION, never replace. Staleness has two sources: git's own facts (`reconcileWorktrees`, via+ // `prunable`) and the status poll's miss-streak. `refresh()` runs on a project switch, on+ // binding another worktree, on deleting a node, on ungrouping — and setting `staleGroupIds`+ // to reconcile's answer alone would ERASE, on any of those, a group the poll had already+ // proven dead: the chip goes healthy again and "↪ Move into worktree" reopens the very window+ // in which it kills a live session into a directory that no longer exists.+ const struck = mine.filter((b) => struckOut(b.worktree.path)).map((b) => b.groupId)+ const staleIds = [...new Set([...stale, ...struck])]+ set({ repoRoot: root, entries, orphans, staleGroupIds: staleIds })} catch {// Fail open: the IPC rejects on a transport error (WS-RPC, Server Edition) and callers are// fire-and-forget effects, so throwing here would only become an unhandled rejection. An@@ -134,8 +149,9 @@ export const useWorktrees = create<WorktreesState>((set) => ({// 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) {- const strikes = (missStreak.get(path) ?? 0) + 1- missStreak.set(path, strikes)+ const key = normWorktreePath(path)+ const strikes = (missStreak.get(key) ?? 0) + 1+ missStreak.set(key, strikes)if (groupId && strikes >= WORKTREE_STALE_STRIKES) {set((s) =>s.staleGroupIds.includes(groupId)@@ -145,7 +161,7 @@ export const useWorktrees = create<WorktreesState>((set) => ({}return}- missStreak.delete(path)+ missStreak.delete(normWorktreePath(path))set((s) => ({// The directory answers again (restored, or a transient read failure passed) → not stale.staleGroupIds:diff --git a/src/shared/worktree-ops.test.ts b/src/shared/worktree-ops.test.tsindex 11e23a2a2..4baf9f0c5 100644--- a/src/shared/worktree-ops.test.ts+++ b/src/shared/worktree-ops.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { worktreeAdd, worktreeMerge, worktreeRemove, type GitExec } from './worktree-ops'+import { worktreeAdd, worktreeList, worktreeMerge, worktreeRemove, type GitExec } from './worktree-ops'const ok = (out = ''): GitExec => ({ ok: true, out, err: '' })const ko = (err = 'fail'): GitExec => ({ ok: false, out: '', err })@@ -41,6 +41,46 @@ describe('worktreeAdd', () => {})})+describe('worktreeList (the git < 2.36 blindness)', () => {+ // git only learned to print `prunable` in 2.36. Debian 11 / Ubuntu 20.04 — the Server Edition's+ // own target platform — ship 2.30, whose porcelain for a worktree whose directory was deleted+ // behind git's back is IDENTICAL to a healthy one (no tag at all). That is what these fixtures+ // are: the porcelain never says `prunable`; only the stat knows the truth.+ const oldGitPorcelain =+ 'worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n' ++ 'worktree /wt/gone\nHEAD bbb\nbranch refs/heads/feature/x\n'++ it('reports a deleted worktree as prunable even when git never tags it (old git)', async () => {+ const { git } = fakeGit({ 'worktree list --porcelain': ok(oldGitPorcelain) })+ const entries = await worktreeList(git, '/repo', async (p) => p !== '/wt/gone')+ expect(entries.map((e) => [e.path, e.prunable])).toEqual([+ ['/repo', false],+ ['/wt/gone', true] // ← the stat fallback, not git+ ])+ })++ it('leaves a worktree whose directory exists alone (no false staleness)', async () => {+ const { git } = fakeGit({ 'worktree list --porcelain': ok(oldGitPorcelain) })+ const entries = await worktreeList(git, '/repo', async () => true)+ expect(entries.every((e) => !e.prunable)).toBe(true)+ })++ it('still honours git´s own prunable tag (git ≥ 2.36) when the stat cannot answer', async () => {+ const modern =+ 'worktree /repo\nHEAD aaa\nbranch refs/heads/main\n\n' ++ 'worktree /wt/gone\nHEAD bbb\nbranch refs/heads/feature/x\nprunable gitdir file points to non-existent location\n'+ const { git } = fakeGit({ 'worktree list --porcelain': ok(modern) })+ // Default pathExists = "everything exists" — the conservative answer; git's tag must still win.+ const entries = await worktreeList(git, '/repo')+ expect(entries.find((e) => e.path === '/wt/gone')?.prunable).toBe(true)+ })++ it('returns nothing when git itself fails (no invented entries)', async () => {+ const { git } = fakeGit({ 'worktree list --porcelain': ko('not a repo') })+ expect(await worktreeList(git, '/repo', async () => false)).toEqual([])+ })+})+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'diff --git a/src/shared/worktree-ops.ts b/src/shared/worktree-ops.tsindex 153690924..37d1de6fa 100644--- a/src/shared/worktree-ops.ts+++ b/src/shared/worktree-ops.ts@@ -29,10 +29,40 @@ export async function repoRoot(git: GitExecutor, cwd: string): Promise<string |return r.ok ? r.out.trim() : null}-export async function worktreeList(git: GitExecutor, repoPath: string): Promise<WorktreeEntry[]> {+/**+ * Does this path exist on disk? Injected (the shared layer has no fs) — the real one is wired in+ * `git-service`. Defaults to "it exists": the conservative answer, which never deletes anything and+ * never calls a live worktree missing.+ */+export type PathExists = (p: string) => Promise<boolean>++const alwaysExists: PathExists = async () => true++/**+ * List a repo's worktrees, with `prunable` made TRUE for any entry whose directory is not on disk.+ *+ * git only emits the `prunable` tag from **2.36**. Debian 11 / Ubuntu 20.04 — the Server Edition's+ * own target platform — ship git 2.30, where a worktree whose directory was deleted behind git's+ * back is listed as perfectly healthy. Everything downstream reads `prunable` as "the directory is+ * gone": `reconcileWorktrees` would call a dead binding live (chip healthy, "↪ Move into worktree"+ * still clickable → it kills a running session and respawns it into a directory that no longer+ * exists) and the bind dialog would offer the vanished directory as an adoptable orphan.+ *+ * So we do not trust the tag alone: stat every entry and OR the result in. Same seam, same+ * conservative default as `worktreeRemove`'s.+ */+export async function worktreeList(+ git: GitExecutor,+ repoPath: string,+ pathExists: PathExists = alwaysExists+): Promise<WorktreeEntry[]> {if (!repoPath) return []const r = await git(repoPath, ['worktree', 'list', '--porcelain'])- return r.ok ? parseWorktreePorcelain(r.out) : []+ if (!r.ok) return []+ const entries = parseWorktreePorcelain(r.out)+ return Promise.all(+ entries.map(async (e) => ({ ...e, prunable: e.prunable || !(await pathExists(e.path)) }))+ )}export async function worktreeAdd(@@ -117,21 +147,16 @@ export async function worktreeMerge(export async function worktreeRemove(git: GitExecutor, repoPath: string, wtPath: string, homeDir: string, deleteBranch: boolean,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+ /** See `PathExists` / `worktreeList`: git's `prunable` flag needs git ≥ 2.36; the stat is the+ * fallback that makes every older git tell the truth about a deleted directory. */+ pathExists: PathExists = alwaysExists): 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.' }if (isDangerousWorktreeRemovalPath(wtPath, repoPath, homeDir)) {return { ok: false, message: 'Refusing to remove that path.' }}- const list = await worktreeList(git, repoPath)+ const list = await worktreeList(git, repoPath, pathExists)const entry = list.find((e) => e.path.replace(/\/+$/, '') === wtPath.replace(/\/+$/, ''))if (!entry) {// Nothing to remove: git does not know this path (deleted + already pruned, or never a