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(git): keep session and worktree branch headers in sync

review7a5b6ded04a0
diff --git a/CLAUDE.md b/CLAUDE.md
index f108819c7..6d58778c1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3843,6 +3843,16 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
the publish flow). Status/history live in the per-cwd `state/scmCache.ts` store (same pattern
as `scmDraft`), so the close→reopen cycle paints the last-known data instantly while the
mount refresh replaces it silently — do not move them back into component `useState`.
+ **Branch observations** (`state/gitBranches.ts`) are shared by Source refreshes, Sessions project
+ headers and existing worktree status polls. They are scoped by GitApi identity + exact cwd + SSH
+ project id, never persisted, and latest-started reads win over late responses. Sessions resolves
+ each project's owning session (including background projects); its header reads the project cwd,
+ while a group header reads only its worktree path. No new timer: sidebar mount/reopen/cwd changes
+ read local checkouts once, Source operations refresh as before, and worktrees keep their existing
+ gated cadence.
+ SSH headers only observe Source refreshes: background SSH connections are not git-routable.
+ Local header probes also skip a cwd claimed by the active SSH route.
+ The branch projection does not replace worktree staleness/ownership decisions or SCM history.
- **Worktrees** (bound to **group frames**) — a git worktree binds to a group node
(`data.worktree: GroupWorktree {repoPath, branch, baseRef, path, createdByApp}`, persisted), and
every node created inside that frame inherits the worktree path as its `cwd`
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0223794bd..95df621bb 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -97,6 +97,13 @@ lane unaffected.
## House rules
+- **Branch labels describe a checkout on one core.** Share existing status reads through
+ `renderer/state/gitBranches.ts`; do not cache a branch forever by project id or copy a project
+ branch onto worktree nodes. Source, Sessions and worktree headers consume the same observations,
+ keyed by API identity, exact cwd and (for SSH) project identity. Never probe an SSH cwd locally
+ from a background header: only the active SSH project is git-routable. SSH headers observe
+ Source refreshes instead.
+
- **Never call the user's machine a Mac in user-visible copy.** Use `thisMachine()` /
`thisMachineCap()` / `machineNoun()` from `src/renderer/lib/machineName.ts` — "this Mac" on
macOS, "this PC" on Windows, "this computer" elsewhere and in any Server Edition browser tab
diff --git a/src/renderer/components/ProjectBranch.test.tsx b/src/renderer/components/ProjectBranch.test.tsx
new file mode 100644
index 000000000..750c0f4d3
--- /dev/null
+++ b/src/renderer/components/ProjectBranch.test.tsx
@@ -0,0 +1,169 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { GitApi, GitStatus, NodeTerminalApi, Project } from '@shared/types'
+import { SessionsSidebar, type SessionsSidebarProps } from './SessionsSidebar'
+import { ProjectBranch } from './ProjectBranch'
+import { SourceControlPanel } from './SourceControlPanel'
+import { readBranchStatus, useGitBranch } from '../state/gitBranches'
+import { useProjects } from '../state/projects'
+import { useSettings } from '../state/settings'
+import { useSshConn } from '../state/sshConn'
+import { createSession, setActiveSession, bindProjectToSession, SessionProvider, resetSessionsForTest } from '../session/session'
+import { ReactFlowProvider } from '@xyflow/react'
+import { GroupNode } from '../nodes/GroupNode'
+import { useWorktrees } from '../state/worktrees'
+
+vi.mock('./git-history/GitHistoryPanel', () => ({ GitHistoryPanel: () => null }))
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+let root: Root
+let host: HTMLDivElement
+const status = (branch: string, hasRepo = true): GitStatus => ({
+ branch, hasRepo, repoName: 'repo', branches: ['main', 'next'], ahead: 0, behind: 0,
+ hasRemote: false, hasOrigin: false, hasUpstream: false, ghAvailable: false, ghAuthed: false,
+ staged: [], changes: []
+})
+const noop = () => {}
+const sidebarProps: SessionsSidebarProps = {
+ open: true, pinned: true, liveActiveNodes: null, onTogglePin: noop, onClose: noop,
+ onFocusNode: noop, onCloseSession: noop, onRenameSession: noop, onAiNameSession: noop,
+ onRowContextMenu: noop, onProjectContextMenu: noop, onSwitchProject: noop, onAddToProject: noop,
+ onMoveToGroup: noop, onAiNameGroup: noop, onReorder: noop, onReorderGroup: noop,
+ onReorderProject: noop, onReopenProject: noop, onDeleteProject: noop,
+ onReopenClosedSession: noop, onDiscardClosedSession: noop, onOpenClosedTranscript: noop
+}
+const project = (id: string, cwd = '/repo') => ({
+ id, cwd, name: id, color: '#fff', nodes: [], viewport: { x: 0, y: 0, zoom: 1 }
+}) as Project
+function apiFor(read = vi.fn(async (_cwd: string) => status('main'))) {
+ return { git: { status: read, history: vi.fn(async () => ({ items: [], hasMore: false })),
+ fetch: vi.fn(async () => ({ ok: true })) }, fs: {} } as unknown as NodeTerminalApi
+}
+function Branch({ git, cwd, sshId }: { git: GitApi; cwd: string; sshId?: string }) {
+ return <output data-cwd={cwd}>{useGitBranch(git, cwd, sshId) ?? 'unknown'}</output>
+}
+async function settle(fn: () => void | Promise<unknown>) { await act(async () => { await fn() }) }
+beforeEach(() => {
+ resetSessionsForTest()
+ window.nodeTerminal = { sshFs: {} } as NodeTerminalApi
+ useProjects.setState({ projects: [], activeProjectId: '' })
+ useSettings.setState((s) => ({ settings: { ...s.settings, gitAutoFetch: false } }))
+ useSshConn.setState({ byProject: {} })
+ host = document.createElement('div'); document.body.append(host); root = createRoot(host)
+})
+afterEach(() => { act(() => root.unmount()); host.remove(); resetSessionsForTest() })
+
+it.each([['/repo', false], ['C:\\repo', false], ['/repo', true]] as const)('Source switch at %s (worktree=%s) updates only its checkout headers', async (cwd, worktreeScope) => {
+ const wt = `${cwd}/worktree`
+ const branches = { [cwd]: 'main', [wt]: 'feature' }
+ const api = apiFor(vi.fn(async (path) => status(branches[path])))
+ api.git.switchBranch = vi.fn(async (path, branch) => { branches[path] = branch; return { ok: true, message: '' } })
+ const sourceCwd = worktreeScope ? wt : cwd
+ const session = createSession('local', api, 'local')
+ setActiveSession(session.id)
+ const p = project('p', cwd)
+ useProjects.setState({ projects: [p], activeProjectId: p.id })
+ await readBranchStatus(api.git, wt)
+ await settle(() => root.render(<SessionProvider session={session}>
+ <SessionsSidebar {...sidebarProps} /><Branch git={api.git} cwd={wt} />
+ <ReactFlowProvider><GroupNode {...({ id: 'wt', data: { title: 'worktree', color: '#fff',
+ worktree: { path: wt, branch: 'saved', repoPath: cwd, baseRef: 'main', createdByApp: true }
+ } } as Parameters<typeof GroupNode>[0])} /></ReactFlowProvider>
+ <SourceControlPanel scopes={[{ id: 'main', label: 'main', cwd }, { id: 'wt', label: 'worktree', cwd: wt }]}
+ defaultScope={{ id: worktreeScope ? 'wt' : 'main', label: 'selected', cwd: sourceCwd }} onClose={() => {}}
+ onRunInTerminal={() => {}} onOpenDiff={() => {}} onOpenCommitDiff={() => {}}
+ onExplainCommit={() => {}} onNewWorktree={() => {}} />
+ </SessionProvider>))
+ expect(host.querySelector('.ss-group__branch')?.textContent).toBe('⎇ main')
+ await settle(() => (document.querySelector('.scm-branch') as HTMLElement).click())
+ const next = [...document.querySelectorAll('button')].find((b) => b.textContent?.trim() === 'next')
+ expect(next).toBeDefined()
+ await settle(() => next!.click())
+ expect(api.git.switchBranch).toHaveBeenCalledWith(sourceCwd, 'next')
+ expect(host.querySelector('.ss-group__branch')?.textContent).toBe(worktreeScope ? '⎇ main' : '⎇ next')
+ expect(host.querySelector('output')?.textContent).toBe(worktreeScope ? 'next' : 'feature')
+ expect(host.querySelector('.group-node__branch')?.textContent).toBe(worktreeScope ? '⎇ next' : '⎇ feature')
+ api.git.switchBranch = vi.fn(async () => ({ ok: false, message: 'fixture: dirty checkout' }))
+ await settle(() => (document.querySelector('.scm-branch') as HTMLElement).click())
+ const main = [...document.querySelectorAll('button')].find((b) => b.textContent?.trim() === 'main')
+ await settle(() => main!.click())
+ expect(document.body.textContent).toContain('fixture: dirty checkout')
+ expect(host.querySelector('.ss-group__branch')?.textContent).toBe(worktreeScope ? '⎇ main' : '⎇ next')
+ // Existing worktree polling publishes to the same branch observation, with no extra read.
+ useWorktrees.getState().reset('p')
+ await settle(() => useWorktrees.getState().refreshStatus(wt))
+ expect(host.querySelector('output')?.textContent).toBe(worktreeScope ? 'next' : 'feature')
+ expect(host.querySelector('.group-node__branch')?.textContent).toBe(worktreeScope ? '⎇ next' : '⎇ feature')
+})
+
+it('keeps same-path cores and SSH projects separate, resolves background projects through their own session', async () => {
+ const a = apiFor(vi.fn(async () => status('local')))
+ const b = apiFor(vi.fn(async () => status('server')))
+ const local = createSession('local', a, 'local')
+ const server = createSession('server', b, 'server')
+ bindProjectToSession('remote', server.id)
+ await settle(() => root.render(<SessionProvider session={server}>
+ <ProjectBranch project={project('local')} /><ProjectBranch project={project('remote')} />
+ <Branch git={a.git} cwd="/repo" sshId="ssh-a" /><Branch git={a.git} cwd="/repo" sshId="ssh-b" />
+ </SessionProvider>))
+ expect([...host.querySelectorAll('.ss-group__branch')].map((e) => e.textContent)).toEqual(['⎇ local', '⎇ server'])
+ await settle(() => readBranchStatus(local.api.git, '/repo', 'ssh-a'))
+ expect([...host.querySelectorAll('output')].map((e) => e.textContent)).toEqual(['local', 'unknown'])
+})
+
+it('SSH headers observe Source, which waits for remote routing; background headers never probe SSH paths', async () => {
+ const api = apiFor()
+ const session = createSession('local', api, 'local')
+ setActiveSession(session.id)
+ const p = { ...project('ssh'), ssh: { remoteCwd: '/remote', server: { host: 'fixture', user: 'test', port: 22 } } } as Project
+ useProjects.setState({ projects: [p], activeProjectId: p.id })
+ await settle(() => root.render(<SessionProvider session={session}>
+ <ProjectBranch project={p} />
+ <SourceControlPanel scopes={[]} onClose={noop} onRunInTerminal={noop} onOpenDiff={noop}
+ onOpenCommitDiff={noop} onExplainCommit={noop} onNewWorktree={noop} />
+ </SessionProvider>))
+ expect(api.git.status).not.toHaveBeenCalled()
+ await settle(() => useSshConn.setState({ byProject: { ssh: { controlPath: '/fixture/socket' } } } as never))
+ expect(api.git.status).toHaveBeenCalledWith('/remote')
+ expect(host.textContent).toBe('⎇ main')
+ vi.mocked(api.git.status).mockClear()
+ const local = project('local', '/remote')
+ // Even a connected SSH header must not probe while its project is in the background. The
+ // local same-path header must also not hit the active SSH routing by mistake.
+ await settle(() => root.render(<SessionProvider session={session}>
+ <ProjectBranch project={p} /><ProjectBranch project={local} />
+ </SessionProvider>))
+ expect(api.git.status).not.toHaveBeenCalled()
+ await settle(() => useProjects.setState({ projects: [p, local], activeProjectId: local.id }))
+ expect(api.git.status).toHaveBeenCalledTimes(1)
+ expect(api.git.status).toHaveBeenCalledWith('/remote')
+})
+
+it('rejects late observations and clears a non-repo result without a render-triggered fetch loop', async () => {
+ let resolveOld!: (s: GitStatus) => void
+ const api = apiFor(vi.fn().mockImplementationOnce(() => new Promise<GitStatus>((r) => { resolveOld = r }))
+ .mockResolvedValueOnce(status('next')).mockResolvedValueOnce(status('', false)))
+ await settle(() => root.render(<Branch git={api.git} cwd="/repo" />))
+ const old = readBranchStatus(api.git, '/repo')
+ await settle(() => readBranchStatus(api.git, '/repo'))
+ await settle(async () => { resolveOld(status('old')); await old })
+ expect(host.textContent).toBe('next')
+ await settle(() => readBranchStatus(api.git, '/repo'))
+ expect(host.textContent).toBe('')
+ expect(api.git.status).toHaveBeenCalledTimes(3)
+})
+
+it('re-resolves a project cwd and re-reads on reopen without retaining its old branch', async () => {
+ const api = apiFor(vi.fn(async (cwd) => status(cwd === '/repo' ? 'main' : 'other')))
+ const session = createSession('local', api, 'local')
+ setActiveSession(session.id)
+ const render = (p?: Project) => root.render(<SessionProvider session={session}>{p && <ProjectBranch project={p} />}</SessionProvider>)
+ await settle(() => render(project('p')))
+ await settle(() => render(project('p', '/other')))
+ expect(host.textContent).toBe('⎇ other')
+ await settle(() => render())
+ await settle(() => render(project('p')))
+ expect(host.textContent).toBe('⎇ main')
+ expect(api.git.status).toHaveBeenCalledTimes(3)
+})
diff --git a/src/renderer/components/ProjectBranch.tsx b/src/renderer/components/ProjectBranch.tsx
new file mode 100644
index 000000000..e9be8264c
--- /dev/null
+++ b/src/renderer/components/ProjectBranch.tsx
@@ -0,0 +1,24 @@
+import { useEffect } from 'react'
+import type { Project } from '@shared/types'
+import { useProjectSession } from '../session/session'
+import { readBranchStatus, useGitBranch } from '../state/gitBranches'
+import { useProjects } from '../state/projects'
+
+/** Project header only. A worktree header reads its OWN checkout, never this project's branch. */
+export function ProjectBranch({ project }: { project: Project }): JSX.Element | null {
+ const git = useProjectSession(project.id).api.git
+ const cwd = project.ssh?.remoteCwd ?? project.cwd
+ const sshId = project.ssh ? project.id : undefined
+ const activeRemoteCwd = useProjects((s) =>
+ s.projects.find((p) => p.id === s.activeProjectId)?.ssh?.remoteCwd)
+ const canRead = !sshId && cwd !== activeRemoteCwd
+ const branch = useGitBranch(git, cwd, sshId)
+ useEffect(() => {
+ // git.status routes ONLY the active SSH project's exact cwd. Background SSH connections
+ // are not routable here, and a local cwd equal to the active remote cwd would hit that host.
+ // SSH headers therefore observe Source's scoped refresh instead of issuing their own read.
+ if (!cwd || !canRead) return
+ void readBranchStatus(git, cwd, sshId).catch(() => {})
+ }, [git, cwd, sshId, canRead])
+ return branch ? <span className="ss-group__branch">⎇ {branch}</span> : null
+}
diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsx
index 722573f77..e15806781 100644
--- a/src/renderer/components/SessionsSidebar.tsx
+++ b/src/renderer/components/SessionsSidebar.tsx
@@ -26,7 +26,7 @@ import { useProjects } from '../state/projects'
import { useSettings } from '../state/settings'
import { useAgentStatus } from '../state/agentStatus'
import { useSessionNaming } from '../state/sessionNaming'
-import { useSession } from '../session/session'
+import { ProjectBranch } from './ProjectBranch'
const HISTORY_COLLAPSE_KEY = 'history'
@@ -87,12 +87,9 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
const activeProjectId = useProjects((s) => s.activeProjectId)
const statusById = useAgentStatus((s) => s.byId)
const namingById = useSessionNaming((s) => s.byId)
- // This sidebar's core api (a stable context read — the branch lookups run on the session's git).
- const { api } = useSession()
const [filter, setFilter] = useState('')
const [statusNow, setStatusNow] = useState(() => Date.now())
- const [branches, setBranches] = useState<Record<string, string>>({})
// Drag-to-group: the object being dragged, and the current drop target for highlighting.
// A group drag also remembers its parent frame, so a sibling-reorder drop zone can refuse a
// drag that came from another container (that move is a REPARENT, which the head handles).
@@ -119,32 +116,6 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
const grouping = useSettings((s) => s.settings.sidebarGrouping)
const updateSettings = useSettings((s) => s.update)
- // Look up the current git branch for each project cwd (best-effort, cached). Gated on `open`
- // and caches a NEGATIVE result too — without the '' fallback a non-git cwd re-fired a git
- // subprocess on every projects-store change, forever.
- useEffect(() => {
- if (!open) return
- let cancelled = false
- projects.forEach((p) => {
- if (!p.cwd || branches[p.id] !== undefined) return
- api.git
- .status(p.cwd)
- .then((st) => {
- if (cancelled) return
- const branch = st && typeof st.branch === 'string' ? st.branch : ''
- setBranches((b) => ({ ...b, [p.id]: branch }))
- })
- .catch(() => {
- if (!cancelled) setBranches((b) => ({ ...b, [p.id]: '' }))
- })
- })
- return () => {
- cancelled = true
- }
- // `api` is a safe dep: this effect only fetches (cancellation flag, no resource), and the
- // local session's api is referentially stable, so adding it changes nothing today.
- }, [open, projects, branches, api])
-
// Gated on `open`: this component stays mounted while the sidebar is closed (the common
// case), and the O(projects × nodes) rebuild re-ran on every agent hook event otherwise.
const groups = useMemo(
@@ -663,9 +634,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
className="ss-group__monogram"
/>
<span className="ss-group__name">{g.projectName}</span>
- {branches[g.projectId] && (
- <span className="ss-group__branch">⎇ {branches[g.projectId]}</span>
- )}
+ <ProjectBranch project={projects.find((p) => p.id === g.projectId)!} />
{signals.attention > 0 && (
<span className="ss-group__sig ss-group__sig--attention" title="Sessions that need you">
<IconBellFilled />
diff --git a/src/renderer/components/SourceControlPanel.tsx b/src/renderer/components/SourceControlPanel.tsx
index a625e9aeb..9c67cf8c4 100644
--- a/src/renderer/components/SourceControlPanel.tsx
+++ b/src/renderer/components/SourceControlPanel.tsx
@@ -10,6 +10,7 @@ import { useProjects } from '../state/projects'
import { useSettings } from '../state/settings'
import { useSshConn } from '../state/sshConn'
import { useScmDraft } from '../state/scmDraft'
+import { readBranchStatus } from '../state/gitBranches'
import { useScmCache } from '../state/scmCache'
import { useSession } from '../session/session'
import { GitHistoryPanel } from './git-history/GitHistoryPanel'
@@ -166,11 +167,12 @@ export function SourceControlPanel({
})
const refresh = useCallback(async () => {
- setStatus(cwd ? await git.status(cwd) : null)
+ if (isSsh && !sshControlPath) return
+ setStatus(cwd ? await readBranchStatus(git, cwd, isSsh ? project?.id : undefined) : null)
// `sshControlPath` is a dep so an SSH project whose master finishes connecting after the panel
// opened re-fetches once the connection is live (instead of staying "no repo"/empty).
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [cwd, git, sshControlPath])
+ }, [cwd, git, sshControlPath, isSsh, project?.id])
const autoFetchOn = useSettings((s) => s.settings.gitAutoFetch)
diff --git a/src/renderer/nodes/GroupNode.tsx b/src/renderer/nodes/GroupNode.tsx
index 324033f13..b9bb8028b 100644
--- a/src/renderer/nodes/GroupNode.tsx
+++ b/src/renderer/nodes/GroupNode.tsx
@@ -7,6 +7,8 @@ import { ungroupNodes, type CanvasNode } from '../state/workspace'
import { NodeColorSwatches } from '../components/NodeColorSwatches'
import { useProjects } from '../state/projects'
import { useWorktrees, WORKTREE_STATUS_POLL_MS } from '../state/worktrees'
+import { useSession } from '../session/session'
+import { useGitBranch } from '../state/gitBranches'
import { useProjectSetup } from '../state/projectSetup'
export type WorktreeAction = 'merge' | 'remove' | 'unbind' | 'rerun-setup'
@@ -64,6 +66,8 @@ export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {
// behaviour is no facts at all, not local facts about a remote checkout.
const sshProject = useProjects((s) => !!s.projects.find((p) => p.id === s.activeProjectId)?.ssh)
const wtPath = sshProject ? undefined : wt?.path
+ const { api } = useSession()
+ const branch = useGitBranch(api.git, wtPath)
// Asking once per render is NOT enough to make the chip live: nothing re-renders a group frame
// while the user works inside its terminals, so the dirty count would freeze at whatever it was
// when the node last happened to render (verified — it sat at "0 changed" until the canvas was
@@ -206,7 +210,7 @@ export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {
<span className="group-node__branch" title={wt.path}>
{/* The branch git reports NOW wins: the user may have switched branches inside
the worktree from a terminal, and the persisted name would then be a lie. */}
- ⎇ {status?.branch || wt.branch}
+ ⎇ {branch || status?.branch || wt.branch}
{!!status && status.dirty > 0 && (
<em className="group-node__wt-dirty" title={`${status.dirty} changed file(s)`}>
{' '}
diff --git a/src/renderer/nodes/group-setup-chip.test.tsx b/src/renderer/nodes/group-setup-chip.test.tsx
index 3c93c20ca..371067941 100644
--- a/src/renderer/nodes/group-setup-chip.test.tsx
+++ b/src/renderer/nodes/group-setup-chip.test.tsx
@@ -9,6 +9,8 @@
import { act } from 'react'
import { createRoot } from 'react-dom/client'
import { describe, expect, it, beforeEach, vi } from 'vitest'
+import type { NodeTerminalApi } from '@shared/types'
+import { SessionProvider, type WorkspaceSession } from '../session/session'
import type { ProjectSetupEvent } from '@shared/project-settings'
import { useProjectSetup } from '../state/projectSetup'
import { useWorktrees } from '../state/worktrees'
@@ -51,7 +53,11 @@ function renderGroup(): { chip: () => HTMLButtonElement | HTMLElement | null; ho
selected: false
} as unknown as Parameters<typeof GroupNode>[0]
act(() => {
- root.render(<GroupNode {...props} />)
+ const session: WorkspaceSession = {
+ id: 'fixture', source: 'local', label: 'fixture', status: 'connected',
+ api: { git: {} } as NodeTerminalApi
+ }
+ root.render(<SessionProvider session={session}><GroupNode {...props} /></SessionProvider>)
})
return { chip: () => host.querySelector('.group-node__setup'), host }
}
diff --git a/src/renderer/state/gitBranches.ts b/src/renderer/state/gitBranches.ts
new file mode 100644
index 000000000..efc63e9a5
--- /dev/null
+++ b/src/renderer/state/gitBranches.ts
@@ -0,0 +1,46 @@
+import { createStore, useStore } from 'zustand'
+import type { GitApi, GitStatus } from '@shared/types'
+
+// Observations only: never persist these or use them to choose a node's cwd. API identity keeps
+// two cores with the same filesystem paths separate; SSH routing also needs the project identity.
+const stores = new WeakMap<GitApi, ReturnType<typeof createBranches>>()
+function createBranches() {
+ return createStore(() => ({ branches: {} as Record<string, string> }))
+}
+function storeFor(git: GitApi) {
+ let store = stores.get(git)
+ if (!store) {
+ store = createBranches()
+ stores.set(git, store)
+ }
+ return store
+}
+const keyFor = (cwd: string, sshProjectId?: string) => JSON.stringify([sshProjectId ?? null, cwd])
+const pending = new WeakMap<GitApi, Map<string, symbol>>()
+
+/** Share an EXISTING status read, without adding a poller. Latest-started read wins, so an old
+ * sidebar/worktree request cannot undo the observation after a Source branch switch. */
+export async function readBranchStatus(git: GitApi, cwd: string, sshProjectId?: string): Promise<GitStatus> {
+ let requests = pending.get(git)
+ if (!requests) {
+ requests = new Map()
+ pending.set(git, requests)
+ }
+ const key = keyFor(cwd, sshProjectId)
+ const token = Symbol()
+ requests.set(key, token)
+ try {
+ const status = await git.status(cwd)
+ if (requests.get(key) === token) {
+ const branch = status.hasRepo ? status.branch : ''
+ storeFor(git).setState((s) => ({ branches: { ...s.branches, [key]: branch } }))
+ }
+ return status
+ } finally {
+ if (requests.get(key) === token) requests.delete(key)
+ }
+}
+
+export function useGitBranch(git: GitApi, cwd?: string, sshProjectId?: string): string | undefined {
+ return useStore(storeFor(git), (s) => cwd ? s.branches[keyFor(cwd, sshProjectId)] : undefined)
+}
diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.ts
index 558e596b4..20a0c74bd 100644
--- a/src/renderer/state/worktrees.ts
+++ b/src/renderer/state/worktrees.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import { readBranchStatus } from './gitBranches'
import { activeSessionApi } from '../session/session'
import {
normWorktreePath,
@@ -221,7 +222,7 @@ export const useWorktrees = create<WorktreesState>((set) => ({
const git = activeSessionApi().git
let status: Awaited<ReturnType<typeof git.status>>
try {
- status = await git.status(path)
+ status = await readBranchStatus(git, 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)