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): renderer store owns repo root, worktree list, throttled status

enes17f83a4f4c68
diff --git a/src/renderer/state/worktrees.test.ts b/src/renderer/state/worktrees.test.ts
new file mode 100644
index 000000000..ac408b6bb
--- /dev/null
+++ b/src/renderer/state/worktrees.test.ts
@@ -0,0 +1,151 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { useWorktrees } from './worktrees'
+
+const gitMock = {
+ repoRoot: vi.fn(),
+ worktreeList: vi.fn(),
+ status: vi.fn()
+}
+
+beforeEach(() => {
+ vi.useRealTimers()
+ gitMock.repoRoot.mockReset()
+ gitMock.worktreeList.mockReset()
+ gitMock.status.mockReset()
+ // Test double for the preload/bridge API (the vitest env is `node`, so there is no real window).
+ ;(globalThis as { window?: unknown }).window = { nodeTerminal: { git: gitMock } }
+ useWorktrees.getState().reset()
+})
+
+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([
+ { path: '/repo', branch: 'main', head: 'a', isBare: false },
+ { path: '/wt/feat', branch: 'feat', head: 'b', isBare: false }
+ ])
+
+ await useWorktrees.getState().refresh('/repo/sub', [])
+
+ expect(gitMock.repoRoot).toHaveBeenCalledWith('/repo/sub')
+ expect(gitMock.worktreeList).toHaveBeenCalledWith('/repo')
+ expect(useWorktrees.getState().repoRoot).toBe('/repo')
+ expect(useWorktrees.getState().entries).toHaveLength(2)
+ })
+
+ it('keeps the entries in git´s order (the main checkout must stay first)', 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 },
+ { path: '/wt/b', branch: 'b', head: 'c', isBare: false }
+ ])
+
+ await useWorktrees.getState().refresh('/repo', [])
+
+ expect(useWorktrees.getState().entries.map((e) => e.path)).toEqual(['/repo', '/wt/a', '/wt/b'])
+ // The main checkout is never offered as a deletable orphan.
+ expect(useWorktrees.getState().orphans.map((o) => o.path)).toEqual(['/wt/a', '/wt/b'])
+ })
+
+ it('classifies stale bindings and orphans', async () => {
+ gitMock.repoRoot.mockResolvedValue('/repo')
+ gitMock.worktreeList.mockResolvedValue([
+ { path: '/repo', branch: 'main', head: 'a', isBare: false },
+ { path: '/wt/loose', branch: 'loose', head: 'c', isBare: false }
+ ])
+
+ await useWorktrees.getState().refresh('/repo', [
+ {
+ groupId: 'g1',
+ worktree: {
+ repoPath: '/repo',
+ branch: 'gone',
+ baseRef: 'main',
+ path: '/wt/gone',
+ createdByApp: true
+ }
+ }
+ ])
+
+ expect(useWorktrees.getState().staleGroupIds).toEqual(['g1'])
+ expect(useWorktrees.getState().orphans.map((o) => o.path)).toEqual(['/wt/loose'])
+ })
+
+ // A group bound to ANOTHER repo's worktree (legacy binding, or hand-typed) must not be
+ // reconciled against this repo's entry list — that would falsely mark it stale, and its
+ // 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([
+ { path: '/repo', branch: 'main', head: 'a', isBare: false }
+ ])
+
+ await useWorktrees.getState().refresh('/repo', [
+ {
+ groupId: 'other',
+ worktree: {
+ repoPath: '/other-repo',
+ branch: 'feat',
+ baseRef: 'main',
+ path: '/other-wt/feat',
+ createdByApp: true
+ }
+ },
+ {
+ groupId: 'mine',
+ worktree: {
+ repoPath: '/repo/',
+ branch: 'gone',
+ baseRef: 'main',
+ path: '/wt/gone',
+ createdByApp: true
+ }
+ }
+ ])
+
+ expect(useWorktrees.getState().staleGroupIds).toEqual(['mine'])
+ })
+
+ it('degrades to empty when the folder is not a git repo (repoRoot null)', async () => {
+ gitMock.repoRoot.mockResolvedValue(null)
+
+ await useWorktrees.getState().refresh('/not/a/repo', [])
+
+ expect(useWorktrees.getState().repoRoot).toBeNull()
+ expect(useWorktrees.getState().entries).toEqual([])
+ expect(gitMock.worktreeList).not.toHaveBeenCalled()
+ })
+})
+
+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
+ })
+
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+
+ expect(useWorktrees.getState().statusByPath['/wt/feat']).toEqual({
+ branch: 'feat',
+ dirty: 3,
+ ahead: 3,
+ behind: 1
+ })
+ })
+
+ // 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 })
+
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+ await useWorktrees.getState().refreshStatus('/wt/feat')
+
+ expect(gitMock.status).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.ts
new file mode 100644
index 000000000..7756d893a
--- /dev/null
+++ b/src/renderer/state/worktrees.ts
@@ -0,0 +1,79 @@
+import { create } from 'zustand'
+import { reconcileWorktrees, type BoundGroup } from '@shared/worktree-reconcile'
+import type { WorktreeEntry } from '@shared/worktree'
+
+/** What the group chip shows. `dirty` = staged + unstaged files. */
+export interface WorktreeStatus {
+ branch: string
+ dirty: number
+ ahead: number
+ behind: number
+}
+
+/** The chip re-renders constantly; without this, every render would spawn a `git status`. */
+export const WORKTREE_STATUS_THROTTLE_MS = 4000
+
+interface WorktreesState {
+ repoRoot: string | null
+ entries: WorktreeEntry[]
+ orphans: WorktreeEntry[]
+ staleGroupIds: string[]
+ statusByPath: Record<string, WorktreeStatus>
+ refresh(projectCwd: string, bound: BoundGroup[]): Promise<void>
+ refreshStatus(path: string): Promise<void>
+ reset(): void
+}
+
+const lastStatusAt = new Map<string, number>()
+
+const normPath = (p: string): string => p.trim().replace(/\/+$/, '')
+
+export const useWorktrees = create<WorktreesState>((set) => ({
+ repoRoot: null,
+ entries: [],
+ orphans: [],
+ staleGroupIds: [],
+ statusByPath: {},
+
+ async refresh(projectCwd, bound) {
+ const git = window.nodeTerminal.git
+ const root = await git.repoRoot(projectCwd)
+ if (!root) {
+ set({ repoRoot: null, entries: [], orphans: [], staleGroupIds: [] })
+ return
+ }
+ // `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 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
+ set((s) => ({
+ statusByPath: {
+ ...s.statusByPath,
+ [path]: {
+ branch: status.branch,
+ dirty: status.staged.length + status.changes.length,
+ ahead: status.ahead,
+ behind: status.behind
+ }
+ }
+ }))
+ },
+
+ reset() {
+ lastStatusAt.clear()
+ set({ repoRoot: null, entries: [], orphans: [], staleGroupIds: [], statusByPath: {} })
+ }
+}))
diff --git a/src/shared/worktree-reconcile.ts b/src/shared/worktree-reconcile.ts
index c3cb35f10..2f0dd7d2f 100644
--- a/src/shared/worktree-reconcile.ts
+++ b/src/shared/worktree-reconcile.ts
@@ -23,6 +23,10 @@ const norm = (p: string): string => p.trim().replace(/\/+$/, '')
* Compare the persisted bindings against `git worktree list`. The FIRST entry git prints is the
* main checkout — it is never an orphan (offering it as one would invite deleting the repo), and
* bare entries are not worktrees a group can own.
+ *
+ * Caller contract: `entries` must be `git worktree list`'s output in git's order (the main checkout
+ * is identified positionally — never sort/filter it first), and `bound` must contain only groups
+ * bound to THAT one repo (groups of another repo would be falsely reported stale).
*/
export function reconcileWorktrees(bound: BoundGroup[], entries: WorktreeEntry[]): Reconciliation {
const usable = entries.filter((e) => !e.isBare)