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 failed `git worktree list` is not an empty one — in the store too

enes153b152d60d4
diff --git a/src/core/git-service.ts b/src/core/git-service.ts
index db856a9e5..678f79cdc 100644
--- a/src/core/git-service.ts
+++ b/src/core/git-service.ts
@@ -234,7 +234,11 @@ export class GitService {
// `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))
+ //
+ // The `{ ok, entries }` shape rides all the way out to the renderer on purpose: an `entries: []`
+ // that came from a FAILED `git worktree list` is not "there are no worktrees", and the store on
+ // the other side of this IPC would otherwise mark every bound group missing on one bad read.
+ return worktreeOps.listWorktrees(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.ts
index be42641f8..b0b02832e 100644
--- a/src/renderer/state/worktrees.test.ts
+++ b/src/renderer/state/worktrees.test.ts
@@ -12,6 +12,13 @@ const okStatus = (over: Partial<Record<string, unknown>> = {}): unknown => ({
...over
})
+/**
+ * A SUCCESSFUL `git worktree list` (the `git:worktree-list` IPC answers `{ ok, entries }`). `ok` is
+ * the whole point: an `ok:false` reply carries the same empty `entries` as a repo with no worktrees,
+ * and the store must never read the first as the second.
+ */
+const listed = (entries: unknown[]): unknown => ({ ok: true, entries })
+
const gitMock = {
repoRoot: vi.fn(),
worktreeList: vi.fn(),
@@ -31,10 +38,10 @@ beforeEach(() => {
describe('useWorktrees.refresh', () => {
it('resolves the repo root from the project cwd and lists that repo´s worktrees', async () => {
gitMock.repoRoot.mockResolvedValue('/repo')
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ path: '/repo', branch: 'main', head: 'a', isBare: false },
{ path: '/wt/feat', branch: 'feat', head: 'b', isBare: false }
- ])
+ ]))
await useWorktrees.getState().refresh('/repo/sub', [])
@@ -46,11 +53,11 @@ describe('useWorktrees.refresh', () => {
it('keeps the entries in git´s order (the main checkout must stay first)', async () => {
gitMock.repoRoot.mockResolvedValue('/repo')
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ path: '/repo', branch: 'main', head: 'a', isBare: false },
{ path: '/wt/a', branch: 'a', head: 'b', isBare: false },
{ path: '/wt/b', branch: 'b', head: 'c', isBare: false }
- ])
+ ]))
await useWorktrees.getState().refresh('/repo', [])
@@ -61,10 +68,10 @@ describe('useWorktrees.refresh', () => {
it('classifies stale bindings and orphans', async () => {
gitMock.repoRoot.mockResolvedValue('/repo')
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ path: '/repo', branch: 'main', head: 'a', isBare: false },
{ path: '/wt/loose', branch: 'loose', head: 'c', isBare: false }
- ])
+ ]))
await useWorktrees.getState().refresh('/repo', [
{
@@ -88,9 +95,9 @@ describe('useWorktrees.refresh', () => {
// terminals would stop inheriting the worktree path.
it('does not mark a group bound to a different repo as stale', async () => {
gitMock.repoRoot.mockResolvedValue('/repo')
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ path: '/repo', branch: 'main', head: 'a', isBare: false }
- ])
+ ]))
await useWorktrees.getState().refresh('/repo', [
{
@@ -291,10 +298,10 @@ describe('useWorktrees.refreshStatus', () => {
// 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([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ 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 }
])
@@ -313,10 +320,10 @@ describe('useWorktrees.refreshStatus', () => {
gitMock.repoRoot.mockResolvedValue('/repo')
// git prunes /wt/gone away entirely (reconcile: stale) and marks /wt/dead prunable.
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ 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 }
@@ -342,10 +349,10 @@ describe('useWorktrees.refreshStatus', () => {
await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')
gitMock.repoRoot.mockResolvedValue('/repo')
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ 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 }
])
@@ -369,15 +376,15 @@ describe('useWorktrees.refreshStatus', () => {
expect(useWorktrees.getState().staleGroupIds).toEqual(['group-1'])
// Unbind: the group is gone from `bound`, and the dead worktree's registration was pruned.
- gitMock.worktreeList.mockResolvedValue([{ path: '/repo', branch: 'main', head: 'a', isBare: false }])
+ gitMock.worktreeList.mockResolvedValue(listed([{ path: '/repo', branch: 'main', head: 'a', isBare: false }]))
await useWorktrees.getState().refresh('/repo', [])
expect(useWorktrees.getState().staleGroupIds).toEqual([])
// The user creates a worktree for the same branch → git hands out the SAME path → a NEW group.
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ path: '/repo', branch: 'main', head: 'a', isBare: false },
{ path: '/wt/feat', branch: 'feat', head: 'b', isBare: false }
- ])
+ ]))
await useWorktrees.getState().refresh('/repo', [
{ groupId: 'group-2', worktree: { path: '/wt/feat', repoPath: '/repo' } as never }
])
@@ -399,7 +406,7 @@ describe('useWorktrees.refreshStatus', () => {
expect(useWorktrees.getState().staleGroupIds).toEqual(['other'])
gitMock.repoRoot.mockResolvedValue('/repo')
- gitMock.worktreeList.mockResolvedValue([{ path: '/repo', branch: 'main', head: 'a', isBare: false }])
+ gitMock.worktreeList.mockResolvedValue(listed([{ path: '/repo', branch: 'main', head: 'a', isBare: false }]))
await useWorktrees.getState().refresh('/repo', [
{ groupId: 'other', worktree: { path: '/other-wt/feat', repoPath: '/other-repo' } as never }
])
@@ -407,6 +414,44 @@ describe('useWorktrees.refreshStatus', () => {
expect(useWorktrees.getState().staleGroupIds).toEqual(['other'])
})
+ // A strike streak is a fact about a live binding, and a binding does not heal while the user looks
+ // at another tab. The streaks used to be wiped on every project switch (and purged by any refresh
+ // that did not own them), so switching to B and back to A gave A's struck-out group a clean slate:
+ // one poll window in which it read healthy — the very window in which `cwdForNewNodeIn` hands out
+ // a path that is gone.
+ it('keeps a project´s strike streak across a switch to another project and back', async () => {
+ const t0 = 1_700_000_000_000
+ vi.useFakeTimers()
+ vi.setSystemTime(t0)
+ const boundA = [{ groupId: 'a1', worktree: { path: '/wt/a', repoPath: '/repo-a' } as never }]
+
+ // Project A: its group strikes out (the directory is gone).
+ useWorktrees.getState().reset('project-a')
+ gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
+ await useWorktrees.getState().refreshStatus('/wt/a', 'a1')
+ vi.setSystemTime(t0 + WORKTREE_STATUS_THROTTLE_MS + 1)
+ await useWorktrees.getState().refreshStatus('/wt/a', 'a1')
+ expect(useWorktrees.getState().staleGroupIds).toEqual(['a1'])
+
+ // Switch to project B (its own bindings; A's streaks are none of its business) …
+ useWorktrees.getState().reset('project-b')
+ gitMock.repoRoot.mockResolvedValue('/repo-b')
+ gitMock.worktreeList.mockResolvedValue(listed([{ path: '/repo-b', branch: 'main', head: 'a', isBare: false }]))
+ await useWorktrees.getState().refresh('/repo-b', [])
+
+ // … and back to A. git still lists /wt/a as healthy (an old git, or a not-yet-re-read list), so
+ // only the surviving streak knows the truth.
+ useWorktrees.getState().reset('project-a')
+ gitMock.repoRoot.mockResolvedValue('/repo-a')
+ gitMock.worktreeList.mockResolvedValue(listed([
+ { path: '/repo-a', branch: 'main', head: 'a', isBare: false },
+ { path: '/wt/a', branch: 'a', head: 'b', isBare: false }
+ ]))
+ await useWorktrees.getState().refresh('/repo-a', boundA)
+
+ expect(useWorktrees.getState().staleGroupIds).toEqual(['a1'])
+ })
+
it('leaves staleness alone when no group id is given', async () => {
gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
@@ -474,10 +519,10 @@ describe('useWorktrees cancellation on reset', () => {
it('drops a refresh that resolves after a reset', async () => {
let releaseRoot: (v: string) => void = () => {}
gitMock.repoRoot.mockReturnValue(new Promise<string>((r) => (releaseRoot = r)))
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ path: '/repo', branch: 'main', head: 'a', isBare: false },
{ path: '/wt/old', branch: 'old', head: 'b', isBare: false }
- ])
+ ]))
const inFlight = useWorktrees.getState().refresh('/repo', [])
useWorktrees.getState().reset()
@@ -491,9 +536,9 @@ describe('useWorktrees cancellation on reset', () => {
it('drops the not-a-repo branch of a refresh that resolves after a reset', async () => {
gitMock.repoRoot.mockResolvedValue('/repo')
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ path: '/repo', branch: 'main', head: 'a', isBare: false }
- ])
+ ]))
await useWorktrees.getState().refresh('/repo', [])
let releaseRoot: (v: string | null) => void = () => {}
@@ -521,16 +566,16 @@ describe('useWorktrees cancellation on reset', () => {
})
describe('useWorktrees.refresh error handling', () => {
- it('swallows an IPC rejection and empties the store (fail open)', async () => {
+ it('swallows a repo-root IPC rejection and empties the store (fail open)', async () => {
gitMock.repoRoot.mockResolvedValue('/repo')
- gitMock.worktreeList.mockResolvedValue([
+ gitMock.worktreeList.mockResolvedValue(listed([
{ path: '/repo', branch: 'main', head: 'a', isBare: false },
{ path: '/wt/a', branch: 'a', head: 'b', isBare: false }
- ])
+ ]))
await useWorktrees.getState().refresh('/repo', [])
expect(useWorktrees.getState().entries).toHaveLength(2)
- gitMock.worktreeList.mockRejectedValue(new Error('bridge closed'))
+ gitMock.repoRoot.mockRejectedValue(new Error('bridge closed'))
await expect(useWorktrees.getState().refresh('/repo', [])).resolves.toBeUndefined()
expect(useWorktrees.getState().repoRoot).toBeNull()
@@ -540,6 +585,59 @@ describe('useWorktrees.refresh error handling', () => {
})
})
+// The IMPORTANT half of this file: `git worktree list` can FAIL (spawn EAGAIN under load, a corrupt
+// index, an unmounted repo) — and a failure arrives with the same empty entry list as a repo that
+// genuinely has no worktrees. Reconciling against it would mark EVERY bound group stale in one read,
+// with none of the strike streak WORKTREE_STALE_STRIKES exists to require: the chip says "· missing",
+// `cwdForNewNodeIn` stops handing out a live worktree path (so a terminal made in that window
+// persists the wrong cwd forever), and Unbind — the only action a stale group offers — rewrites the
+// children's persisted cwds off a perfectly healthy worktree.
+describe('useWorktrees.refresh when the worktree LIST could not be read', () => {
+ const bound = [
+ { groupId: 'g1', worktree: { repoPath: '/repo', path: '/wt/feat', branch: 'feat', baseRef: 'main', createdByApp: true } }
+ ]
+ const healthy = listed([
+ { path: '/repo', branch: 'main', head: 'a', isBare: false },
+ { path: '/wt/feat', branch: 'feat', head: 'b', isBare: false }
+ ])
+
+ it('does not stale a bound group when the list comes back ok:false', async () => {
+ gitMock.repoRoot.mockResolvedValue('/repo')
+ gitMock.worktreeList.mockResolvedValue(healthy)
+ await useWorktrees.getState().refresh('/repo', bound)
+ expect(useWorktrees.getState().staleGroupIds).toEqual([])
+
+ // git could not be read — the SAME empty list a worktree-less repo would answer with.
+ gitMock.worktreeList.mockResolvedValue({ ok: false, entries: [] })
+ await useWorktrees.getState().refresh('/repo', bound)
+
+ expect(useWorktrees.getState().staleGroupIds).toEqual([])
+ // The previous (successful) facts stand — a failed read changed nothing.
+ expect(useWorktrees.getState().entries.map((e) => e.path)).toEqual(['/repo', '/wt/feat'])
+ expect(useWorktrees.getState().repoRoot).toBe('/repo')
+ })
+
+ it('a REJECTED list is the same fact as ok:false — it must not empty the store either', async () => {
+ gitMock.repoRoot.mockResolvedValue('/repo')
+ gitMock.worktreeList.mockResolvedValue(healthy)
+ await useWorktrees.getState().refresh('/repo', bound)
+
+ gitMock.worktreeList.mockRejectedValue(new Error('bridge closed'))
+ await expect(useWorktrees.getState().refresh('/repo', bound)).resolves.toBeUndefined()
+
+ expect(useWorktrees.getState().staleGroupIds).toEqual([])
+ expect(useWorktrees.getState().entries.map((e) => e.path)).toEqual(['/repo', '/wt/feat'])
+ })
+
+ it('an ok:true empty list still marks the group stale (a real absence IS evidence)', async () => {
+ gitMock.repoRoot.mockResolvedValue('/repo')
+ gitMock.worktreeList.mockResolvedValue(listed([{ path: '/repo', branch: 'main', head: 'a', isBare: false }]))
+ await useWorktrees.getState().refresh('/repo', bound)
+
+ expect(useWorktrees.getState().staleGroupIds).toEqual(['g1'])
+ })
+})
+
describe('useWorktrees.refresh interleaving without reset', () => {
// Two rapid refresh calls without an intervening reset would previously race: both capture the
// same epoch, so the older project's in-flight reads would overwrite the newer project's facts.
@@ -549,10 +647,10 @@ describe('useWorktrees.refresh interleaving without reset', () => {
it('a newer refresh always supersedes an in-flight older one', async () => {
let releaseRootA: (v: string) => void = () => {}
- let releaseListA: (v: unknown[]) => void = () => {}
+ let releaseListA: (v: unknown) => void = () => {}
const promiseRootA = new Promise<string>((r) => (releaseRootA = r))
- const promiseListA = new Promise<unknown[]>((r) => (releaseListA = r))
+ const promiseListA = new Promise<unknown>((r) => (releaseListA = r))
// Track which cwd/root is being queried and return appropriate promises.
gitMock.repoRoot.mockImplementation((cwd: string) => {
@@ -562,10 +660,12 @@ describe('useWorktrees.refresh interleaving without reset', () => {
gitMock.worktreeList.mockImplementation((root: string) => {
if (root === '/repo-a') return promiseListA
- return Promise.resolve([
- { path: '/repo-b', branch: 'main', head: 'b1', isBare: false },
- { path: '/wt/b-feat', branch: 'b-feat', head: 'b2', isBare: false }
- ])
+ return Promise.resolve(
+ listed([
+ { path: '/repo-b', branch: 'main', head: 'b1', isBare: false },
+ { path: '/wt/b-feat', branch: 'b-feat', head: 'b2', isBare: false }
+ ])
+ )
})
// Start refresh for repo A (in flight, blocked on our controlled promises).
@@ -579,10 +679,12 @@ describe('useWorktrees.refresh interleaving without reset', () => {
// Now let A finish. Even though A resolves after B, the epoch bump ensures A's older
// epoch is stale and its write is dropped.
releaseRootA('/repo-a')
- releaseListA([
- { path: '/repo-a', branch: 'main', head: 'a1', isBare: false },
- { path: '/wt/a-old', branch: 'a-old', head: 'a2', isBare: false }
- ])
+ releaseListA(
+ listed([
+ { path: '/repo-a', branch: 'main', head: 'a1', isBare: false },
+ { path: '/wt/a-old', branch: 'a-old', head: 'a2', isBare: false }
+ ])
+ )
await refreshA
// The store must hold B's facts, not A's. If the epoch is not bumped per-refresh, A's later
diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.ts
index 25c8db875..c73e1ed8c 100644
--- a/src/renderer/state/worktrees.ts
+++ b/src/renderer/state/worktrees.ts
@@ -48,19 +48,46 @@ interface WorktreesState {
* answering again un-marks it.
*/
refreshStatus(path: string, groupId?: string): Promise<void>
- reset(): void
+ /**
+ * Drop the previous project's worktree facts. `projectKey` (the project id) scopes the strike
+ * streaks that survive the switch — see `missStreak`. Call it on every project load, including the
+ * ones that never `refresh()` (SSH, or a project with no cwd), so no project can inherit another's
+ * scope.
+ */
+ reset(projectKey?: string): void
}
const lastStatusAt = new Map<string, number>()
/**
* 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.
+ * success. Keyed by the NORMALIZED path (so `refresh` can look a binding up in it) PREFIXED BY THE
+ * PROJECT the streak was observed in.
+ *
+ * The scope is what lets a streak outlive a project switch. It is a fact about a live binding, and
+ * bindings do not stop being dead while the user looks at another tab: without the prefix the map
+ * had to be wiped on every switch (and `refresh` purged every key its own project did not own), so
+ * switching to B and back to A forgot A's strikes and A's dead group rendered healthy for a poll
+ * window — the very window in which `cwdForNewNodeIn` hands out a path that is gone.
*/
const missStreak = new Map<string, number>()
+/**
+ * The project the strikes below belong to. Set by `reset`, which the active-project effect fires on
+ * EVERY project load (a project that never refreshes — SSH, no cwd — must still get its own scope,
+ * or it would file its strikes under the last project that did). Only the ACTIVE project's groups
+ * ever poll, so one scope at a time is all this needs.
+ */
+let streakScope = ''
+
+/** Separates the scope from the path in a streak key. A project id and a path can both contain
+ * most characters; a NUL cannot appear in either, so the key can never be ambiguous. */
+const STREAK_SEP = '\u0000'
+
+/** Streak key: the project that observed it + the normalized worktree path. */
+const streakKey = (p: string): string => `${streakScope}${STREAK_SEP}${normWorktreePath(p)}`
+
/** 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
+const struckOut = (p: string): boolean => (missStreak.get(streakKey(p)) ?? 0) >= WORKTREE_STALE_STRIKES
/**
* Cancellation token for the in-flight async reads. `refresh`/`refreshStatus` are fired from React
@@ -103,8 +130,25 @@ export const useWorktrees = create<WorktreesState>((set) => ({
return
}
// `entries` stays in git's order — reconcileWorktrees identifies the main checkout positionally.
- const entries = await git.worktreeList(root)
+ // A REJECTION here (a dead WS bridge in the Server Edition) is the same fact as `ok:false` —
+ // the list could not be read — so it must not fall through to the catch below, which empties
+ // the store and would take every group's staleness (and every orphan) with it.
+ const listed = await git
+ .worktreeList(root)
+ .catch(() => ({ ok: false, entries: [] as WorktreeEntry[] }))
if (mineEpoch !== epoch) return
+ if (!listed.ok) {
+ // git could not be READ (spawn EAGAIN under load, a corrupt index, an unmounted repo). That
+ // is not "this repo has no worktrees": reconciling against the empty list would mark EVERY
+ // bound group stale on one bad read — no strike streak, no second opinion — which is exactly
+ // the escalation WORKTREE_STALE_STRIKES exists to forbid, and it costs the user real things
+ // (`cwdForNewNodeIn` stops handing out a healthy worktree path, and the only action a stale
+ // group offers — Unbind — rewrites its children's persisted cwds off a live worktree).
+ // So: change nothing. The previous facts stand until a read actually succeeds.
+ set({ repoRoot: root })
+ return
+ }
+ const entries = listed.entries
// A miss-streak is a fact about a BINDING, not about a path forever. It is keyed by path and
// `computeWorktreePath` is deterministic, so a streak that outlives its binding comes back to
// haunt the next one: delete a worktree dir → the group strikes out → Unbind (which prunes)
@@ -113,8 +157,14 @@ export const useWorktrees = create<WorktreesState>((set) => ({
// until the next successful poll. So the moment a path is no longer bound to any group
// (unbind / remove / ungroup / delete — all of which re-refresh), forget its streak.
// Only BOUND paths are ever consulted below, so nothing else can depend on it.
- const boundPaths = new Set(bound.map((b) => normWorktreePath(b.worktree.path)))
- for (const key of [...missStreak.keys()]) if (!boundPaths.has(key)) missStreak.delete(key)
+ //
+ // Scoped to THIS project's keys: another project's streaks are none of this refresh's
+ // business (its `bound` list does not describe them), and deleting them was what made a
+ // dead group read healthy again after a there-and-back project switch.
+ const boundKeys = new Set(bound.map((b) => streakKey(b.worktree.path)))
+ const mineKey = (k: string): boolean => k.startsWith(`${streakScope}${STREAK_SEP}`)
+ for (const key of [...missStreak.keys()])
+ if (mineKey(key) && !boundKeys.has(key)) missStreak.delete(key)
// Reconcile only the groups bound to THIS repo. A group bound to another repo's worktree
// (legacy binding, or hand-typed) would otherwise be compared against the wrong entry list
// and falsely reported stale.
@@ -165,7 +215,7 @@ 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 key = normWorktreePath(path)
+ const key = streakKey(path)
const strikes = (missStreak.get(key) ?? 0) + 1
missStreak.set(key, strikes)
if (groupId && strikes >= WORKTREE_STALE_STRIKES) {
@@ -177,7 +227,7 @@ export const useWorktrees = create<WorktreesState>((set) => ({
}
return
}
- missStreak.delete(normWorktreePath(path))
+ missStreak.delete(streakKey(path))
set((s) => ({
// The directory answers again (restored, or a transient read failure passed) → not stale.
staleGroupIds:
@@ -197,10 +247,14 @@ export const useWorktrees = create<WorktreesState>((set) => ({
}))
},
- reset() {
+ reset(projectKey = '') {
epoch++
+ streakScope = projectKey
lastStatusAt.clear()
- missStreak.clear()
+ // `missStreak` is deliberately NOT cleared: it is scoped per project (see missStreak), and a
+ // switch away from a project does not resurrect its dead worktrees. Clearing it here handed a
+ // struck-out group a clean slate on every switch-back — one poll window in which it looked
+ // healthy. Its keys are pruned by `refresh` (per project), not by the switch.
set({ ...empty(), statusByPath: {} })
}
}))
diff --git a/src/shared/types.ts b/src/shared/types.ts
index ba3663eed..306bca15f 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -608,7 +608,9 @@ export interface GitApi {
/** Checkout a commit (detached HEAD). */
checkoutCommit(cwd: string, oid: string): Promise<GitResult>
repoRoot(cwd: string): Promise<string | null>
- worktreeList(repoPath: string): Promise<import('./worktree').WorktreeEntry[]>
+ /** `{ ok: false, entries: [] }` when git itself could not be read — which is NOT the same fact as
+ * "this repo has no worktrees", and no caller may treat it as one (see worktree-ops). */
+ worktreeList(repoPath: string): Promise<import('./worktree').WorktreeListResult>
worktreeAdd(repoPath: string, wtPath: string, branch: string, baseRef: string, isNew: boolean): 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. */
diff --git a/src/shared/worktree-ops.test.ts b/src/shared/worktree-ops.test.ts
index 34b952d28..48e12ef7d 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, worktreeList, worktreeMerge, worktreeRemove, type GitExec } from './worktree-ops'
+import { worktreeAdd, listWorktrees, 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,7 +41,7 @@ describe('worktreeAdd', () => {
})
})
-describe('worktreeList (the git < 2.36 blindness)', () => {
+describe('listWorktrees (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
@@ -52,7 +52,7 @@ describe('worktreeList (the git < 2.36 blindness)', () => {
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')
+ const { entries } = await listWorktrees(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
@@ -61,7 +61,7 @@ describe('worktreeList (the git < 2.36 blindness)', () => {
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)
+ const { entries } = await listWorktrees(git, '/repo', async () => true)
expect(entries.every((e) => !e.prunable)).toBe(true)
})
@@ -71,13 +71,26 @@ describe('worktreeList (the git < 2.36 blindness)', () => {
'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')
+ const { entries } = await listWorktrees(git, '/repo')
expect(entries.find((e) => e.path === '/wt/gone')?.prunable).toBe(true)
})
- it('returns nothing when git itself fails (no invented entries)', async () => {
+ it('says ok:false when git itself fails — an empty list is NOT proof of absence', async () => {
const { git } = fakeGit({ 'worktree list --porcelain': ko('not a repo') })
- expect(await worktreeList(git, '/repo', async () => false)).toEqual([])
+ // The entries are empty EITHER WAY; `ok` is the only thing that can tell the two apart, and it
+ // is what stops one transient failure from marking every bound group missing.
+ expect(await listWorktrees(git, '/repo', async () => false)).toEqual({ ok: false, entries: [] })
+ })
+
+ it('says ok:true for a repo that genuinely has no worktrees listed', async () => {
+ const { git } = fakeGit({ 'worktree list --porcelain': ok('') })
+ expect(await listWorktrees(git, '/repo')).toEqual({ ok: true, entries: [] })
+ })
+
+ it('says ok:false without calling git when there is no repo path', async () => {
+ const { git, calls } = fakeGit({})
+ expect(await listWorktrees(git, '')).toEqual({ ok: false, entries: [] })
+ expect(calls.length).toBe(0)
})
})
diff --git a/src/shared/worktree-ops.ts b/src/shared/worktree-ops.ts
index 0e4d48809..3ed8ec995 100644
--- a/src/shared/worktree-ops.ts
+++ b/src/shared/worktree-ops.ts
@@ -3,7 +3,7 @@ import {
isDangerousWorktreeRemovalPath,
decideMergeStrategy,
isValidGitRef,
- type WorktreeEntry
+ type WorktreeListResult
} from './worktree'
/** One git invocation's result (mirrors git-service.ts's internal `Exec`). */
@@ -50,33 +50,23 @@ const alwaysExists: PathExists = async () => true
*
* 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[]> {
- return (await listWorktrees(git, repoPath, pathExists)).entries
-}
-
-/**
- * `worktreeList`, plus WHETHER GIT COULD BE READ AT ALL.
*
- * `worktreeList` collapses both outcomes to `[]`: "git listed nothing" and "the git call failed"
- * (spawn EAGAIN under load, an unmounted/NFS repo, a corrupt index) are the same empty array. For a
- * chip that is fine — it just shows nothing. For the DESTRUCTIVE paths it is not: `worktreeRemove`
- * read the empty list as "this worktree is not registered — it is already gone", answered
- * `worktreeGone`, and the renderer then destroyed every descendant terminal's tmux session (running
- * processes and all), reset their persisted cwds and dropped the binding — while the directory and
- * its registration sat untouched on disk. One unverified read must never escalate to destruction
- * (the same principle as `WORKTREE_STALE_STRIKES`), so the ops that act on the answer take this
- * shape instead and refuse when `ok` is false.
+ * It also reports WHETHER GIT COULD BE READ AT ALL, and every caller — the ops below AND the
+ * renderer's worktrees store, which reaches this through the `git:worktree-list` IPC — must honour
+ * that flag. Collapsing both outcomes to `[]` ("git listed nothing" and "the git call failed": a
+ * spawn EAGAIN under load, an unmounted/NFS repo, a corrupt index) is what let a single transient
+ * failure escalate: `worktreeRemove` read the empty list as "this worktree is not registered — it is
+ * already gone", answered `worktreeGone`, and the renderer destroyed every descendant terminal's
+ * tmux session (running processes and all) while the directory sat untouched on disk; and
+ * `reconcileWorktrees([], …)` flipped EVERY healthy bound group to "missing" in one read, with none
+ * of the strike streak `WORKTREE_STALE_STRIKES` exists to require. A failed read is never evidence
+ * of absence — so it is never dressed up as one.
*/
-async function listWorktrees(
+export async function listWorktrees(
git: GitExecutor,
repoPath: string,
- pathExists: PathExists
-): Promise<{ ok: boolean; entries: WorktreeEntry[] }> {
+ pathExists: PathExists = alwaysExists
+): Promise<WorktreeListResult> {
if (!repoPath) return { ok: false, entries: [] }
const r = await git(repoPath, ['worktree', 'list', '--porcelain'])
if (!r.ok) return { ok: false, entries: [] }