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): guard the store against stale writes, IPC failures and dead worktrees

enes6d510389221a
diff --git a/src/renderer/state/worktrees.test.ts b/src/renderer/state/worktrees.test.ts
index ac408b6bb..3a46eaa85 100644
--- a/src/renderer/state/worktrees.test.ts
+++ b/src/renderer/state/worktrees.test.ts
@@ -1,5 +1,16 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest'
-import { useWorktrees } from './worktrees'
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { useWorktrees, WORKTREE_STATUS_THROTTLE_MS } from './worktrees'
+
+/** A `git status` on a healthy worktree, with only the fields the store reads spelled out. */
+const okStatus = (over: Partial<Record<string, unknown>> = {}): unknown => ({
+ hasRepo: true,
+ branch: 'feat',
+ staged: [],
+ changes: [],
+ ahead: 0,
+ behind: 0,
+ ...over
+})
const gitMock = {
repoRoot: vi.fn(),
@@ -120,13 +131,9 @@ describe('useWorktrees.refresh', () => {
describe('useWorktrees.refreshStatus', () => {
it('maps a git status into the chip´s numbers', async () => {
- gitMock.status.mockResolvedValue({
- branch: 'feat',
- staged: [{ path: 'a' }],
- changes: [{ path: 'b' }, { path: 'c' }],
- ahead: 3,
- behind: 1
- })
+ gitMock.status.mockResolvedValue(
+ okStatus({ staged: [{ path: 'a' }], changes: [{ path: 'b' }, { path: 'c' }], ahead: 3, behind: 1 })
+ )
await useWorktrees.getState().refreshStatus('/wt/feat')
@@ -141,11 +148,164 @@ describe('useWorktrees.refreshStatus', () => {
// The chip re-renders on every canvas interaction; without a throttle each one would
// spawn a `git status` subprocess.
it('throttles repeated calls for the same path', async () => {
- gitMock.status.mockResolvedValue({ branch: 'feat', staged: [], changes: [], ahead: 0, behind: 0 })
+ gitMock.status.mockResolvedValue(okStatus())
await useWorktrees.getState().refreshStatus('/wt/feat')
await useWorktrees.getState().refreshStatus('/wt/feat')
expect(gitMock.status).toHaveBeenCalledTimes(1)
})
+
+ // Pins the throttle WINDOW, not just its existence: a throttle that never expired would pass
+ // the test above but leave the chip frozen on its first reading forever.
+ it('lets a call through again once the throttle window has expired', async () => {
+ const t0 = 1_700_000_000_000
+ vi.useFakeTimers()
+ vi.setSystemTime(t0)
+ gitMock.status.mockResolvedValue(okStatus())
+
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+ vi.setSystemTime(t0 + WORKTREE_STATUS_THROTTLE_MS - 1)
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+ expect(gitMock.status).toHaveBeenCalledTimes(1)
+
+ vi.setSystemTime(t0 + WORKTREE_STATUS_THROTTLE_MS + 1)
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+ expect(gitMock.status).toHaveBeenCalledTimes(2)
+ })
+
+ // `git.status()` does NOT throw on a path that is no longer a repo (the worktree was deleted
+ // outside the app): core/git-service returns an empty status with hasRepo:false. Writing that
+ // would render a dead worktree as a healthy one with a blank branch — `staleGroupIds` is what
+ // tells that story.
+ it('ignores a status for a path that is not a repo (hasRepo false)', async () => {
+ gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))
+
+ await useWorktrees.getState().refreshStatus('/wt/gone')
+
+ expect(useWorktrees.getState().statusByPath['/wt/gone']).toBeUndefined()
+ })
+
+ // Callers fire this from React effects; over the Server Edition's WS-RPC bridge a transport
+ // error REJECTS, which would become an unhandled rejection.
+ it('swallows an IPC rejection and leaves the previous status intact', async () => {
+ gitMock.status.mockResolvedValue(okStatus({ ahead: 2 }))
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+
+ lastStatusWindowExpired()
+ gitMock.status.mockRejectedValue(new Error('bridge closed'))
+ await expect(useWorktrees.getState().refreshStatus('/wt/feat')).resolves.toBeUndefined()
+
+ expect(useWorktrees.getState().statusByPath['/wt/feat']).toEqual({
+ branch: 'feat',
+ dirty: 0,
+ ahead: 2,
+ behind: 0
+ })
+ })
+
+ // The throttle stamp is taken before the await; if a failure kept it, the chip would be locked
+ // out of retrying for the whole window over a transient error.
+ it('does not burn the throttle window on a failed call', async () => {
+ gitMock.status.mockRejectedValueOnce(new Error('nope')).mockResolvedValue(okStatus())
+
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+
+ expect(gitMock.status).toHaveBeenCalledTimes(2)
+ expect(useWorktrees.getState().statusByPath['/wt/feat']?.branch).toBe('feat')
+ })
+
+ it('reset() clears the collected statuses', async () => {
+ gitMock.status.mockResolvedValue(okStatus())
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+ expect(useWorktrees.getState().statusByPath['/wt/feat']).toBeDefined()
+
+ useWorktrees.getState().reset()
+
+ expect(useWorktrees.getState().statusByPath).toEqual({})
+ })
+})
+
+/** Push the clock past the throttle window without touching the (real-timer) default. */
+function lastStatusWindowExpired(): void {
+ const now = Date.now()
+ vi.useFakeTimers()
+ vi.setSystemTime(now + WORKTREE_STATUS_THROTTLE_MS + 1)
+}
+
+// `refresh`/`refreshStatus` are async with no cancellation, and are fired from React effects on
+// project switch. A stale in-flight call resolving AFTER the switch would overwrite the new
+// project's facts with the old project's — and Task 3 creates worktrees under `repoRoot` while
+// Task 4 offers `orphans` for deletion, so a stale write is live ammunition.
+describe('useWorktrees cancellation on reset', () => {
+ afterEach(() => vi.useRealTimers())
+
+ 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([
+ { 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()
+ releaseRoot('/repo')
+ await inFlight
+
+ expect(useWorktrees.getState().repoRoot).toBeNull()
+ expect(useWorktrees.getState().entries).toEqual([])
+ expect(useWorktrees.getState().orphans).toEqual([])
+ })
+
+ it('drops the not-a-repo branch of a refresh that resolves after a reset', async () => {
+ gitMock.repoRoot.mockResolvedValue('/repo')
+ gitMock.worktreeList.mockResolvedValue([
+ { path: '/repo', branch: 'main', head: 'a', isBare: false }
+ ])
+ await useWorktrees.getState().refresh('/repo', [])
+
+ let releaseRoot: (v: string | null) => void = () => {}
+ gitMock.repoRoot.mockReturnValue(new Promise<string | null>((r) => (releaseRoot = r)))
+ const inFlight = useWorktrees.getState().refresh('/other', [])
+ useWorktrees.getState().reset()
+ releaseRoot(null)
+ await inFlight
+
+ // reset() already emptied the store; the stale call must not write to it at all.
+ expect(useWorktrees.getState().repoRoot).toBeNull()
+ })
+
+ it('drops a status that resolves after a reset', async () => {
+ let releaseStatus: (v: unknown) => void = () => {}
+ gitMock.status.mockReturnValue(new Promise((r) => (releaseStatus = r)))
+
+ const inFlight = useWorktrees.getState().refreshStatus('/wt/feat')
+ useWorktrees.getState().reset()
+ releaseStatus(okStatus())
+ await inFlight
+
+ expect(useWorktrees.getState().statusByPath).toEqual({})
+ })
+})
+
+describe('useWorktrees.refresh error handling', () => {
+ it('swallows an IPC rejection and empties the store (fail open)', async () => {
+ gitMock.repoRoot.mockResolvedValue('/repo')
+ gitMock.worktreeList.mockResolvedValue([
+ { 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'))
+ await expect(useWorktrees.getState().refresh('/repo', [])).resolves.toBeUndefined()
+
+ expect(useWorktrees.getState().repoRoot).toBeNull()
+ expect(useWorktrees.getState().entries).toEqual([])
+ expect(useWorktrees.getState().orphans).toEqual([])
+ expect(useWorktrees.getState().staleGroupIds).toEqual([])
+ })
})
diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.ts
index 7756d893a..e868299a7 100644
--- a/src/renderer/state/worktrees.ts
+++ b/src/renderer/state/worktrees.ts
@@ -1,5 +1,9 @@
import { create } from 'zustand'
-import { reconcileWorktrees, type BoundGroup } from '@shared/worktree-reconcile'
+import {
+ normWorktreePath,
+ reconcileWorktrees,
+ type BoundGroup
+} from '@shared/worktree-reconcile'
import type { WorktreeEntry } from '@shared/worktree'
/** What the group chip shows. `dirty` = staged + unstaged files. */
@@ -26,7 +30,23 @@ interface WorktreesState {
const lastStatusAt = new Map<string, number>()
-const normPath = (p: string): string => p.trim().replace(/\/+$/, '')
+/**
+ * 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,
+ * so the OLD project's call can still resolve afterwards and win the last write — leaving project B
+ * holding project A's `repoRoot` and orphan list. Since worktrees are CREATED under `repoRoot` and
+ * orphans are offered for DELETION, that stale write is not cosmetic. Every `set` is therefore
+ * gated on the epoch the call started in.
+ */
+let epoch = 0
+
+/** "No worktree facts" — what a non-repo project, a failed read and a reset all collapse to. */
+const empty = (): Pick<WorktreesState, 'repoRoot' | 'entries' | 'orphans' | 'staleGroupIds'> => ({
+ repoRoot: null,
+ entries: [],
+ orphans: [],
+ staleGroupIds: []
+})
export const useWorktrees = create<WorktreesState>((set) => ({
repoRoot: null,
@@ -36,29 +56,54 @@ export const useWorktrees = create<WorktreesState>((set) => ({
statusByPath: {},
async refresh(projectCwd, bound) {
+ const mineEpoch = epoch
const git = window.nodeTerminal.git
- const root = await git.repoRoot(projectCwd)
- if (!root) {
- set({ repoRoot: null, entries: [], orphans: [], staleGroupIds: [] })
- return
+ try {
+ const root = await git.repoRoot(projectCwd)
+ if (mineEpoch !== epoch) return
+ if (!root) {
+ set(empty())
+ return
+ }
+ // `entries` stays in git's order — reconcileWorktrees identifies the main checkout positionally.
+ const entries = await git.worktreeList(root)
+ if (mineEpoch !== epoch) return
+ // 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.
+ const mine = bound.filter(
+ (b) => normWorktreePath(b.worktree.repoPath) === normWorktreePath(root)
+ )
+ const { stale, orphans } = reconcileWorktrees(mine, entries)
+ set({ repoRoot: root, entries, orphans, staleGroupIds: stale })
+ } 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
+ // empty store means "no worktree facts" — every consumer already degrades to that.
+ if (mineEpoch !== epoch) return
+ set(empty())
}
- // `entries` stays in git's order — reconcileWorktrees identifies the main checkout positionally.
- const entries = await git.worktreeList(root)
- // 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.
- const mine = bound.filter((b) => normPath(b.worktree.repoPath) === normPath(root))
- const { stale, orphans } = reconcileWorktrees(mine, entries)
- set({ repoRoot: root, entries, orphans, staleGroupIds: stale })
},
async refreshStatus(path) {
+ const mineEpoch = epoch
const now = Date.now()
const prev = lastStatusAt.get(path) ?? 0
if (now - prev < WORKTREE_STATUS_THROTTLE_MS) return
lastStatusAt.set(path, now)
- const status = await window.nodeTerminal.git.status(path)
- if (!status) return
+ let status: Awaited<ReturnType<typeof window.nodeTerminal.git.status>>
+ try {
+ status = await window.nodeTerminal.git.status(path)
+ } catch {
+ // Un-stamp, or a transient failure would lock the chip out of retrying for the whole window.
+ if (lastStatusAt.get(path) === now) lastStatusAt.delete(path)
+ return
+ }
+ 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 keep the last known status instead.
+ if (!status.hasRepo) return
set((s) => ({
statusByPath: {
...s.statusByPath,
@@ -73,7 +118,8 @@ export const useWorktrees = create<WorktreesState>((set) => ({
},
reset() {
+ epoch++
lastStatusAt.clear()
- set({ repoRoot: null, entries: [], orphans: [], staleGroupIds: [], statusByPath: {} })
+ set({ ...empty(), statusByPath: {} })
}
}))
diff --git a/src/shared/worktree-reconcile.ts b/src/shared/worktree-reconcile.ts
index 2f0dd7d2f..eabb7a25b 100644
--- a/src/shared/worktree-reconcile.ts
+++ b/src/shared/worktree-reconcile.ts
@@ -17,7 +17,10 @@ export interface Reconciliation {
orphans: WorktreeEntry[]
}
-const norm = (p: string): string => p.trim().replace(/\/+$/, '')
+/** Compare worktree paths as git prints them vs. as we persisted them: trailing slashes differ. */
+export const normWorktreePath = (p: string): string => p.trim().replace(/\/+$/, '')
+
+const norm = normWorktreePath
/**
* Compare the persisted bindings against `git worktree list`. The FIRST entry git prints is the