The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): scope coding rail + review pane per worktree cwd
Brooklyn Nicholson2e3e9c176544
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex 2a957564066..b05b563c528 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -1188,7 +1188,10 @@ export function ChatBar({onBranchOff={handleBranchOff}onConvertBranch={handleConvertBranch}onListBranches={handleListBranches}- onOpen={toggleReview}+ // A tile's rail reviews ITS worktree: pin the pane's scope to+ // this surface's cwd. Main keeps the classic follow-the-+ // active-session scope (null).+ onOpen={() => toggleReview(scope.target === 'main' ? null : (cwd ?? null))}onOpenWorktree={openInWorktree}onSwitchBranch={handleSwitchBranch}repoPath={cwd}diff --git a/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx b/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsxindex 14cb89d3ddc..6ad820765e5 100644--- a/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx@@ -15,7 +15,13 @@ import { Codicon } from '@/components/ui/codicon'import { DiffCount } from '@/components/ui/diff-count'import type { HermesGitBranch } from '@/global'import { useI18n } from '@/i18n'-import { $repoStatus, $repoWorktrees } from '@/store/coding-status'+import {+ $repoStatus,+ $repoWorktrees,+ registerRepoStatusCwd,+ repoStatusForCwd,+ repoWorktreesForCwd+} from '@/store/coding-status'import { notifyError } from '@/store/notifications'import { $newWorktreeRequest } from '@/store/projects'@@ -62,14 +68,21 @@ export const CodingStatusRow = memo(function CodingStatusRow({const { t } = useI18n()const s = t.statusStack.codingconst p = t.sidebar.projects- const status = useStore($repoStatus)- const worktrees = useStore($repoWorktrees)+ const resolvedRepoPath = repoPath?.trim() || undefined+ // Per-cwd slice when this surface knows its worktree (tiles); otherwise the+ // primary main-pane computed — so a blank/missing repoPath still paints.+ const status = useStore(resolvedRepoPath ? repoStatusForCwd(resolvedRepoPath) : $repoStatus)+ const worktrees = useStore(resolvedRepoPath ? repoWorktreesForCwd(resolvedRepoPath) : $repoWorktrees)++ // While mounted, keep this worktree in the coding-status refresh set so the+ // turn-settle / tool-complete / focus edges re-probe it too (tiles otherwise+ // only refreshed when the MAIN cwd probe happened to cover them).+ useEffect(() => registerRepoStatusCwd(resolvedRepoPath), [resolvedRepoPath])// Shared worktree dialog — replaces the old inline dialog. Opened by the// dropdown menu's "branch off" items and the global ⌘⇧B hotkey.const [worktreeOpen, setWorktreeOpen] = useState(false)const [worktreeBase, setWorktreeBase] = useState<string | undefined>(undefined)- const resolvedRepoPath = repoPath?.trim() || undefinedconst switchToBranch = async (branch: string) => {if (!onSwitchBranch) {diff --git a/apps/desktop/src/app/right-sidebar/review/file-tree.tsx b/apps/desktop/src/app/right-sidebar/review/file-tree.tsxindex 7878fab719b..5a89f0eb8ba 100644--- a/apps/desktop/src/app/right-sidebar/review/file-tree.tsx+++ b/apps/desktop/src/app/right-sidebar/review/file-tree.tsx@@ -26,9 +26,11 @@ import {$reviewFiles,$reviewLoading,$reviewOpen,+ $reviewScopeCwd,$reviewSelectedPath,$reviewTreeMode,requestRevert,+ reviewRepoCwd,selectReviewFile,stageReviewFile,unstageReviewFile@@ -54,16 +56,13 @@ const STATUS_GLYPH: Record<string, { icon: string; tone: string }> = {}// Review paths are repo-relative; the composer drop expects absolute paths, so-// join against the active session cwd (the repo we probed).+// join against the pane's repo (its pinned scope, else the active session cwd).function absolutePath(relative: string): string {if (/^([a-zA-Z]:[\\/]|\/)/.test(relative)) {return relative}- const cwd = $currentCwd- .get()- ?.trim()- .replace(/[\\/]+$/, '')+ const cwd = reviewRepoCwd()?.replace(/[\\/]+$/, '')return cwd ? `${cwd}/${relative}` : relative}@@ -237,7 +236,11 @@ function ReviewFileRow({ node, depth }: { node: ReviewTreeNode; depth: number })const selected = file.path === selectedPathconst glyph = STATUS_GLYPH[file.status] ?? STATUS_GLYPH.Mconst dragPath = absolutePath(file.path)- const cwd = useStore($currentCwd)+ // Reactive mirror of reviewRepoCwd(): the pinned scope wins, else the+ // active session's cwd (subscribing to both keeps the row live either way).+ const scopeCwd = useStore($reviewScopeCwd)+ const activeCwd = useStore($currentCwd)+ const cwd = scopeCwd?.trim() || activeCwd// Single-click shows the inline diff; double-click opens the file in the main// preview pane (matching the file browser). They're mutually exclusive: deferdiff --git a/apps/desktop/src/components/assistant-ui/thread/changed-files-card.tsx b/apps/desktop/src/components/assistant-ui/thread/changed-files-card.tsxindex e1b60012dbb..7d043eea672 100644--- a/apps/desktop/src/components/assistant-ui/thread/changed-files-card.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/changed-files-card.tsx@@ -1,5 +1,7 @@import { type FC, useMemo } from 'react'+import { useStore } from '@nanostores/react'+import { useSessionView } from '@/app/chat/session-view'import { deriveChangedFiles } from '@/components/assistant-ui/thread/changed-files'import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'import { DiffCount } from '@/components/ui/diff-count'@@ -20,6 +22,11 @@ export const ChangedFilesCard: FC<{ parts: readonly unknown[] }> = ({ parts }) =const { t } = useI18n()const copy = t.assistant.threadconst files = useMemo(() => deriveChangedFiles(parts), [parts])+ // Review THIS surface's repo: a tile transcript pins the pane to the tile's+ // worktree; the primary passes null (follow the active session, as before).+ const view = useSessionView()+ const viewCwd = useStore(view.$cwd)+ const scopeCwd = view.kind === 'primary' ? null : viewCwd || nullif (files.length === 0) {return null@@ -34,7 +41,7 @@ export const ChangedFilesCard: FC<{ parts: readonly unknown[] }> = ({ parts }) =<span className="min-w-0 flex-1 truncate text-(--ui-text-primary)">{copy.filesChanged(files.length)}</span><buttonclassName="shrink-0 cursor-pointer text-(--ui-text-tertiary) transition-colors hover:text-(--ui-text-primary)"- onClick={revealReview}+ onClick={() => revealReview(scopeCwd)}type="button">{copy.reviewChanges}@@ -45,7 +52,7 @@ export const ChangedFilesCard: FC<{ parts: readonly unknown[] }> = ({ parts }) =<buttonclassName="row-hover -mx-1.5 flex items-center gap-2 rounded-md px-1.5 py-1 text-left"key={file.path}- onClick={() => void openReviewForPath(file.path)}+ onClick={() => void openReviewForPath(file.path, scopeCwd)}title={file.path}type="button">diff --git a/apps/desktop/src/store/coding-status.test.ts b/apps/desktop/src/store/coding-status.test.tsindex 204b4772633..e73069ec4c5 100644--- a/apps/desktop/src/store/coding-status.test.ts+++ b/apps/desktop/src/store/coding-status.test.ts@@ -2,7 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { HermesRepoStatus } from '@/global'-import { $repoStatus, $repoStatusLoading, refreshRepoStatus } from './coding-status'+import {+ $repoStatus,+ $repoStatusByCwd,+ $repoStatusLoading,+ _resetCodingStatusForTests,+ refreshAllRepoStatuses,+ registerRepoStatusCwd,+ refreshRepoStatus,+ repoStatusForCwd+} from './coding-status'import { $currentCwd, $selectedStoredSessionId } from './session'const sampleStatus: HermesRepoStatus = {@@ -21,6 +30,16 @@ const sampleStatus: HermesRepoStatus = {files: []}+const otherStatus: HermesRepoStatus = {+ ...sampleStatus,+ branch: 'bb/other-worktree',+ added: 3,+ removed: 1,+ changed: 1,+ staged: 0,+ unstaged: 1+}+function stubProbe(impl: (cwd: string) => Promise<HermesRepoStatus | null>) {;(window as unknown as { hermesDesktop?: unknown }).hermesDesktop = { git: { repoStatus: impl } }}@@ -28,21 +47,27 @@ function stubProbe(impl: (cwd: string) => Promise<HermesRepoStatus | null>) {describe('refreshRepoStatus', () => {beforeEach(() => {vi.useFakeTimers()- $repoStatus.set(null)+ _resetCodingStatusForTests()$currentCwd.set('')$selectedStoredSessionId.set(null)+ // Drain the cwd/session subscribe side-effects the sets above kick off.+ vi.advanceTimersByTime(200)delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+ _resetCodingStatusForTests()})afterEach(() => {+ _resetCodingStatusForTests()vi.clearAllTimers()vi.useRealTimers()delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop})- it('populates $repoStatus from the probe for an explicit cwd', async () => {+ it('populates the per-cwd cache and the primary computed for that cwd', async () => {stubProbe(async () => sampleStatus)+ $currentCwd.set('/repo')await refreshRepoStatus('/repo')+ expect(repoStatusForCwd('/repo').get()).toEqual(sampleStatus)expect($repoStatus.get()).toEqual(sampleStatus)})@@ -52,31 +77,47 @@ describe('refreshRepoStatus', () => {$currentCwd.set('/active/repo')await refreshRepoStatus()expect(probe).toHaveBeenCalledWith('/active/repo')+ expect($repoStatus.get()).toEqual(sampleStatus)})- it('clears status when there is no cwd', async () => {+ it('leaves the cache alone (primary reads null) when there is no cwd', async () => {stubProbe(async () => sampleStatus)- $repoStatus.set(sampleStatus)+ $currentCwd.set('/repo')+ await refreshRepoStatus('/repo')+ expect($repoStatus.get()).toEqual(sampleStatus)++ // Blank target is a no-op: other worktrees' cached truth must stay put.await refreshRepoStatus(' ')+ expect(repoStatusForCwd('/repo').get()).toEqual(sampleStatus)+ $currentCwd.set('')expect($repoStatus.get()).toBeNull()})- it('clears status when the probe is unavailable (remote backend)', async () => {- $repoStatus.set(sampleStatus)+ it('clears every cached status when the probe is unavailable (remote backend)', async () => {+ $currentCwd.set('/repo')+ $repoStatusByCwd.set({ '/repo': sampleStatus, '/other': otherStatus })await refreshRepoStatus('/repo')+ expect($repoStatusByCwd.get()).toEqual({})expect($repoStatus.get()).toBeNull()})- it('clears status when the probe throws', async () => {- stubProbe(async () => {- throw new Error('not a repo')+ it('clears only the failing cwd when the probe throws', async () => {+ stubProbe(async cwd => {+ if (cwd === '/bad') {+ throw new Error('not a repo')+ }++ return sampleStatus})- $repoStatus.set(sampleStatus)- await refreshRepoStatus('/repo')+ $currentCwd.set('/bad')+ $repoStatusByCwd.set({ '/bad': otherStatus, '/good': sampleStatus })+ await refreshRepoStatus('/bad')+ expect(repoStatusForCwd('/bad').get()).toBeNull()+ expect(repoStatusForCwd('/good').get()).toEqual(sampleStatus)expect($repoStatus.get()).toBeNull()})- it('never publishes an old worktree status after the active cwd moves', async () => {+ it('never publishes an old worktree status onto the primary after the active cwd moves', async () => {let resolveOld!: (status: HermesRepoStatus | null) => voidstubProbe(() =>@@ -85,23 +126,40 @@ describe('refreshRepoStatus', () => {}))+ // Explicit probe (not the debounced cwd edge) so the hang is fully under+ // our control — same race window the coding rail used to hit after a+ // session switch mid-probe.+ const inflight = refreshRepoStatus('/repo-a')$currentCwd.set('/repo-a')- vi.advanceTimersByTime(200)- await vi.runAllTicks()+ await Promise.resolve()- // The first probe is still in flight when the user switches sessions. The- // new cwd's probe is intentionally debounced, so this is the exact window- // where Ctrl+Shift+B used to see the old branch in the coding rail.$currentCwd.set('/repo-b')expect($repoStatus.get()).toBeNull()resolveOld(sampleStatus)- await vi.runAllTicks()+ await inflight+ // Primary follows the NEW cwd (empty). The old worktree may still cache the+ // late result under its own key — that's what lets a tile rail paint+ // instantly — but it must not leak onto the main rail via $repoStatus.expect($repoStatus.get()).toBeNull()+ expect(repoStatusForCwd('/repo-a').get()).toEqual(sampleStatus)})- it('runs one probe at a time and coalesces overlap into one trailing refresh', async () => {+ it('keeps independent statuses for two live worktrees', async () => {+ stubProbe(async cwd => (cwd === '/repo-a' ? sampleStatus : otherStatus))+ await refreshRepoStatus('/repo-a')+ await refreshRepoStatus('/repo-b')+ expect(repoStatusForCwd('/repo-a').get()).toEqual(sampleStatus)+ expect(repoStatusForCwd('/repo-b').get()).toEqual(otherStatus)++ $currentCwd.set('/repo-a')+ expect($repoStatus.get()).toEqual(sampleStatus)+ $currentCwd.set('/repo-b')+ expect($repoStatus.get()).toEqual(otherStatus)+ })++ it('runs one probe at a time and coalesces overlap into one trailing refresh per drain', async () => {const resolvers: Array<(status: HermesRepoStatus | null) => void> = []const calls: string[] = []let active = 0@@ -120,6 +178,7 @@ describe('refreshRepoStatus', () => {}))+ $currentCwd.set('/repo-c')const first = refreshRepoStatus('/repo-a')const second = refreshRepoStatus('/repo-b')const third = refreshRepoStatus('/repo-c')@@ -132,14 +191,20 @@ describe('refreshRepoStatus', () => {await Promise.resolve()await Promise.resolve()- expect(calls).toEqual(['/repo-a', '/repo-c'])expect(maxActive).toBe(1)- expect($repoStatus.get()).toBeNull()+ expect(calls.length).toBe(2)+ resolvers.shift()?.(otherStatus)+ await Promise.resolve()+ await Promise.resolve()resolvers.shift()?.(sampleStatus)await Promise.all([first, second, third])expect(maxActive).toBe(1)+ expect(calls).toEqual(['/repo-a', '/repo-b', '/repo-c'])+ expect(repoStatusForCwd('/repo-a').get()).toEqual(sampleStatus)+ expect(repoStatusForCwd('/repo-b').get()).toEqual(otherStatus)+ expect(repoStatusForCwd('/repo-c').get()).toEqual(sampleStatus)expect($repoStatus.get()).toEqual(sampleStatus)expect($repoStatusLoading.get()).toBe(false)})@@ -166,4 +231,27 @@ describe('refreshRepoStatus', () => {expect(probe).toHaveBeenCalledWith('/repo')})++ it('registerRepoStatusCwd keeps that worktree in unscoped refreshes', async () => {+ const probe = vi.fn(async cwd => (cwd === '/tile' ? otherStatus : sampleStatus))+ stubProbe(probe)++ $currentCwd.set('/main')+ const release = registerRepoStatusCwd('/tile')+ // Drain the register kick + cwd edge so the assert only covers the+ // unscoped fan-out.+ vi.advanceTimersByTime(200)+ await refreshAllRepoStatuses()+ probe.mockClear()++ // Unscoped fan-out: every registered worktree + primary, not main only.+ await refreshAllRepoStatuses()++ const probed = [...new Set(probe.mock.calls.map(call => call[0]))].sort()+ expect(probed).toEqual(['/main', '/tile'])+ expect(repoStatusForCwd('/tile').get()).toEqual(otherStatus)+ expect(repoStatusForCwd('/main').get()).toEqual(sampleStatus)++ release?.()+ })})diff --git a/apps/desktop/src/store/coding-status.ts b/apps/desktop/src/store/coding-status.tsindex 578a378f763..4a1ea97b0c1 100644--- a/apps/desktop/src/store/coding-status.ts+++ b/apps/desktop/src/store/coding-status.ts@@ -1,4 +1,4 @@-import { atom, computed } from 'nanostores'+import { atom, computed, type ReadableAtom } from 'nanostores'import type { HermesGitWorktree, HermesRepoStatus } from '@/global'import { desktopGit } from '@/lib/desktop-git'@@ -7,20 +7,88 @@ import { $worktreeRefreshToken } from './projects'import { $busy, $currentCwd, $selectedStoredSessionId } from './session'import { $workspaceChangeTick } from './workspace-events'-// Live working-tree status for the active session's cwd — the data backbone of-// the composer coding rail. It's the same "cheaply re-read git truth at the-// right moments" model as the sidebar worktree probe: a single bounded-// `git status --porcelain=v2` per refresh, driven by structural edges (cwd-// change, turn settle, window focus, worktree mutation), never per-token and-// never touching the conversation/system-prompt cache.+// Live working-tree status for every git surface on screen — the data backbone+// of the composer coding rail. Keyed PER CWD: the main pane and each session+// tile can sit in different worktrees, so a single global status would paint+// the primary repo's branch/± onto every rail (the "tile shows main's diff"+// bug). It's the same "cheaply re-read git truth at the right moments" model+// as the sidebar worktree probe: a single bounded `git status --porcelain=v2`+// per on-screen worktree per refresh, driven by structural edges (cwd change,+// turn settle, window focus, worktree mutation), never per-token and never+// touching the conversation/system-prompt cache.++const REPO_STATUS_REFRESH_DEBOUNCE_MS = 100++const normalizeCwd = (cwd?: null | string): null | string => cwd?.trim() || null++const EMPTY_WORKTREES: HermesGitWorktree[] = []++// Status + worktrees per normalized cwd. Entries outlive their surface (the+// map stays bounded by the worktrees touched this run) so re-opening a tile+// paints its last-known status instantly while the fresh probe runs.+export const $repoStatusByCwd = atom<Record<string, HermesRepoStatus | null>>({})+export const $repoWorktreesByCwd = atom<Record<string, HermesGitWorktree[]>>({})++// The PRIMARY (main pane) view — the active session's slice of the per-cwd+// truth. Existing consumers (keybind gate, base-branch picker, file tree) keep+// reading these; only surfaces that can live in ANOTHER worktree (tile rails)+// need the per-cwd accessors below.+export const $repoStatus: ReadableAtom<HermesRepoStatus | null> = computed(+ [$repoStatusByCwd, $currentCwd],+ (byCwd, cwd) => byCwd[normalizeCwd(cwd) ?? ''] ?? null+)-export const $repoStatus = atom<HermesRepoStatus | null>(null)export const $repoStatusLoading = atom(false)// The repo's real worktrees (for the coding rail's "jump to a worktree" menu).// Refreshed on the same edges as the status probe; empty off a repo.-export const $repoWorktrees = atom<HermesGitWorktree[]>([])-const REPO_STATUS_REFRESH_DEBOUNCE_MS = 100+export const $repoWorktrees: ReadableAtom<HermesGitWorktree[]> = computed(+ [$repoWorktreesByCwd, $currentCwd],+ (byCwd, cwd) => byCwd[normalizeCwd(cwd) ?? ''] ?? EMPTY_WORKTREES+)++// Reference-stable per-cwd slices, so any number of rails can each subscribe+// to their own worktree's status without re-deriving atoms per render.+const statusAtomByCwd = new Map<string, ReadableAtom<HermesRepoStatus | null>>()+const worktreesAtomByCwd = new Map<string, ReadableAtom<HermesGitWorktree[]>>()+const $noRepoStatus = atom<HermesRepoStatus | null>(null)+const $noWorktrees = atom<HermesGitWorktree[]>(EMPTY_WORKTREES)++/** Reactive status for one repo cwd (a tile's worktree). Stable per cwd. */+export function repoStatusForCwd(cwd?: null | string): ReadableAtom<HermesRepoStatus | null> {+ const key = normalizeCwd(cwd)++ if (!key) {+ return $noRepoStatus+ }++ let $slice = statusAtomByCwd.get(key)++ if (!$slice) {+ $slice = computed($repoStatusByCwd, byCwd => byCwd[key] ?? null)+ statusAtomByCwd.set(key, $slice)+ }++ return $slice+}++/** Reactive worktree list for one repo cwd. Stable per cwd. */+export function repoWorktreesForCwd(cwd?: null | string): ReadableAtom<HermesGitWorktree[]> {+ const key = normalizeCwd(cwd)++ if (!key) {+ return $noWorktrees+ }++ let $slice = worktreesAtomByCwd.get(key)++ if (!$slice) {+ $slice = computed($repoWorktreesByCwd, byCwd => byCwd[key] ?? EMPTY_WORKTREES)+ worktreesAtomByCwd.set(key, $slice)+ }++ return $slice+}export type RepoChangeKind = 'added' | 'conflicted' | 'modified'@@ -44,28 +112,64 @@ export const $repoChangeByPath = computed([$repoStatus, $currentCwd], (status, creturn map})-async function loadWorktrees(target: string): Promise<void> {- const list = desktopGit()?.worktreeList+// Cwds whose rails are on screen right now (refcounted — two tiles in one+// worktree register it twice). Every refresh edge re-probes each registered+// cwd plus the primary workspace, so a tile's rail moves when ITS agent+// touches the tree — not only when main's does.+const registeredCwds = new Map<string, number>()- if (!list) {- $repoWorktrees.set([])+/** Keep `cwd` in the refresh set while its rail is mounted. Returns a release+ * (undefined for a blank cwd), kicking off an immediate probe on register. */+export function registerRepoStatusCwd(cwd?: null | string): (() => void) | undefined {+ const key = normalizeCwd(cwd)- return+ if (!key) {+ return undefined}- try {- const worktrees = await list(target)+ registeredCwds.set(key, (registeredCwds.get(key) ?? 0) + 1)+ scheduleRepoStatusRefresh(key)- if (inflightCwd === target && statusStillBelongsToActiveCwd(target)) {- $repoWorktrees.set(worktrees)+ let released = false++ return () => {+ if (released) {+ return}- } catch {- if (inflightCwd === target && statusStillBelongsToActiveCwd(target)) {- $repoWorktrees.set([])++ released = true+ const count = registeredCwds.get(key) ?? 0++ if (count <= 1) {+ registeredCwds.delete(key)+ } else {+ registeredCwds.set(key, count - 1)}}}+function setRepoStatusEntry(target: string, status: HermesRepoStatus | null): void {+ const byCwd = $repoStatusByCwd.get()++ // Skip the no-op null→null write so a repeated failed probe doesn't churn+ // every rail's computed slice.+ if (target in byCwd && byCwd[target] === status) {+ return+ }++ $repoStatusByCwd.set({ ...byCwd, [target]: status })+}++function setRepoWorktreesEntry(target: string, worktrees: HermesGitWorktree[]): void {+ const byCwd = $repoWorktreesByCwd.get()++ if (target in byCwd && byCwd[target] === worktrees) {+ return+ }++ $repoWorktreesByCwd.set({ ...byCwd, [target]: worktrees })+}+interface RepoStatusRefreshRequest {probe: (cwd: string) => Promise<HermesRepoStatus | null>seq: number@@ -73,61 +177,81 @@ interface RepoStatusRefreshRequest {}// Coalesce overlapping probes: many triggers can fire around a turn boundary-// (busy flip + worktree token + focus), but only the latest cwd matters. Keep-// one probe in flight and retain at most one trailing request so a slow Git-// status cannot multiply into an unbounded subprocess pile-up.-let inflightCwd: null | string = null-let pendingRepoStatusRefresh: RepoStatusRefreshRequest | null = null+// (busy flip + worktree token + focus), and several worktrees can need a+// re-probe at once. Keep ONE probe in flight and at most one trailing request+// per cwd so a slow `git status` cannot multiply into an unbounded subprocess+// pile-up.+const seqByCwd = new Map<string, number>()+const pendingByCwd = new Map<string, RepoStatusRefreshRequest>()let repoStatusRefreshInFlight: Promise<void> | null = null-let repoStatusRefreshSeq = 0let repoStatusRefreshTimer: ReturnType<typeof setTimeout> | null = null+const scheduledCwds = new Set<string>()+let scheduledAllTargets = false-const normalizeCwd = (cwd?: null | string): null | string => cwd?.trim() || null+// A result only lands while it is still the newest request for ITS cwd. The+// debounce below deliberately delays the next probe; without this live check,+// an old probe can land during that gap and briefly make a session look like+// it is on a stale branch.+const isCurrentSeq = (target: string, seq: number): boolean => seqByCwd.get(target) === seq-// A result only belongs in the global rail while it still describes the active-// workspace. The debounce below deliberately delays the next probe; without-// this live check, an old probe can land during that gap and briefly make a new-// session look like it is on the previous worktree's branch.-const statusStillBelongsToActiveCwd = (target: string): boolean => {- const active = normalizeCwd($currentCwd.get())+async function loadWorktrees(target: string, seq: number): Promise<void> {+ const list = desktopGit()?.worktreeList++ if (!list) {+ setRepoWorktreesEntry(target, EMPTY_WORKTREES)++ return+ }- return !active || active === target+ try {+ const worktrees = await list(target)++ if (isCurrentSeq(target, seq)) {+ setRepoWorktreesEntry(target, worktrees)+ }+ } catch {+ if (isCurrentSeq(target, seq)) {+ setRepoWorktreesEntry(target, EMPTY_WORKTREES)+ }+ }}/**- * Re-probe the working tree for `cwd` (defaults to the active session's cwd).- * Best-effort: a non-repo, a remote backend, or a missing probe clears the- * status so the rail hides rather than showing stale data.+ * Re-probe the working tree for one cwd. Best-effort: a non-repo, a remote+ * backend, or a missing probe clears that cwd's entry so its rail hides+ * rather than showing stale data.*/async function runRepoStatusRefresh({ probe, seq, target }: RepoStatusRefreshRequest): Promise<void> {try {const status = await probe(target)- // Drop the result if the cwd moved on while we were probing (a fast session- // switch) — the newer probe owns the atom.- if (seq === repoStatusRefreshSeq && inflightCwd === target && statusStillBelongsToActiveCwd(target)) {- $repoStatus.set(status)+ // Drop the result if a newer refresh for this cwd started while we were+ // probing — the newer probe owns the entry.+ if (!isCurrentSeq(target, seq)) {+ return+ }- // Worktrees only matter inside a repo; clear them otherwise.- if (status) {- void loadWorktrees(target)- } else {- $repoWorktrees.set([])- }+ setRepoStatusEntry(target, status)++ // Worktrees only matter inside a repo; clear them otherwise.+ if (status) {+ void loadWorktrees(target, seq)+ } else {+ setRepoWorktreesEntry(target, EMPTY_WORKTREES)}} catch {- if (seq === repoStatusRefreshSeq && inflightCwd === target && statusStillBelongsToActiveCwd(target)) {- $repoStatus.set(null)- $repoWorktrees.set([])+ if (isCurrentSeq(target, seq)) {+ setRepoStatusEntry(target, null)+ setRepoWorktreesEntry(target, EMPTY_WORKTREES)}}}async function drainRepoStatusRefreshes(): Promise<void> {- while (pendingRepoStatusRefresh) {- const request = pendingRepoStatusRefresh+ while (pendingByCwd.size > 0) {+ const [target, request] = pendingByCwd.entries().next().value as [string, RepoStatusRefreshRequest]- pendingRepoStatusRefresh = null+ pendingByCwd.delete(target)await runRepoStatusRefresh(request)}@@ -141,20 +265,30 @@ async function drainRepoStatusRefreshes(): Promise<void> {export function refreshRepoStatus(cwd?: null | string): Promise<void> {const target = normalizeCwd(cwd ?? $currentCwd.get())const probe = desktopGit()?.repoStatus- const seq = (repoStatusRefreshSeq += 1)- if (!target || !probe) {- pendingRepoStatusRefresh = null- inflightCwd = null- $repoStatus.set(null)- $repoWorktrees.set([])+ if (!probe) {+ // Remote backend / no bridge: there is no local git truth at all — wipe+ // every entry so no rail shows stale local status, and invalidate any+ // in-flight probe results.+ pendingByCwd.clear()+ seqByCwd.clear()+ $repoStatusByCwd.set({})+ $repoWorktreesByCwd.set({})$repoStatusLoading.set(false)return repoStatusRefreshInFlight || Promise.resolve()}- inflightCwd = target- pendingRepoStatusRefresh = { probe, seq, target }+ if (!target) {+ // No cwd (a detached fresh chat). The primary computed already reads null+ // for a blank cwd, and other worktrees' entries stay valid.+ return repoStatusRefreshInFlight || Promise.resolve()+ }++ const seq = (seqByCwd.get(target) ?? 0) + 1++ seqByCwd.set(target, seq)+ pendingByCwd.set(target, { probe, seq, target })$repoStatusLoading.set(true)if (!repoStatusRefreshInFlight) {@@ -164,30 +298,82 @@ export function refreshRepoStatus(cwd?: null | string): Promise<void> {return repoStatusRefreshInFlight}+/** Registered (on-screen) worktrees + the primary workspace. */+function refreshTargets(): Set<string> {+ const targets = new Set(registeredCwds.keys())+ const primary = normalizeCwd($currentCwd.get())++ if (primary) {+ targets.add(primary)+ }++ return targets+}++/** Re-probe every on-screen worktree (and the primary). Awaits the drain. */+export async function refreshAllRepoStatuses(): Promise<void> {+ const targets = refreshTargets()++ if (targets.size === 0) {+ return+ }++ // Queue every target, then await the single in-flight drain once.+ let last: Promise<void> = Promise.resolve()++ for (const target of targets) {+ last = refreshRepoStatus(target)+ }++ await last+}++// `cwd` scopes the refresh to one worktree; omit it to re-probe every+// on-screen worktree (turn settle, window focus — the tree may have changed+// under any of them).function scheduleRepoStatusRefresh(cwd?: null | string): void {+ if (cwd === undefined) {+ scheduledAllTargets = true+ } else {+ const key = normalizeCwd(cwd)++ if (key) {+ scheduledCwds.add(key)+ }+ }+if (repoStatusRefreshTimer) {clearTimeout(repoStatusRefreshTimer)}repoStatusRefreshTimer = setTimeout(() => {repoStatusRefreshTimer = null- void refreshRepoStatus(cwd)+ const targets = new Set(scheduledCwds)++ if (scheduledAllTargets) {+ for (const target of refreshTargets()) {+ targets.add(target)+ }+ }++ scheduledCwds.clear()+ scheduledAllTargets = false++ for (const target of targets) {+ void refreshRepoStatus(target)+ }}, REPO_STATUS_REFRESH_DEBOUNCE_MS)}// ── Triggers ─────────────────────────────────────────────────────────────────// Wired once at module load (mirrors projects.ts's module-scope subscriptions).-// Each is a structural edge where the working tree may have changed under us.--// The active session's cwd changed (session switch / new chat) → immediately-// hide the old repo's facts, then re-probe after the small debounce. This makes-// keyboard actions safe in the switch-to-probe gap: Ctrl+Shift+B cannot use a-// still-painted branch label from the previous worktree.-$currentCwd.subscribe(cwd => {- $repoStatus.set(null)- $repoWorktrees.set([])- scheduleRepoStatusRefresh(cwd)-})+// Each is a structural edge where a working tree may have changed under us.++// The active session's cwd changed (session switch / new chat) → the primary+// computed re-keys instantly (a keyboard action in the switch-to-probe gap can+// only ever see the NEW repo's last-known facts, never the previous+// worktree's), then the debounced probe refreshes that repo's truth.+$currentCwd.subscribe(cwd => scheduleRepoStatusRefresh(cwd))// Switching sessions can land on the same cwd but a different checked-out// branch (the agent ran `git checkout` in another session's terminal). The cwd@@ -201,7 +387,9 @@ $selectedStoredSessionId.subscribe(() => scheduleRepoStatusRefresh())$worktreeRefreshToken.subscribe(() => scheduleRepoStatusRefresh())// A file-mutating tool finished (event-driven, not polled) → re-probe so the-// rail's branch/+/- move exactly when the agent touches the tree.+// rails' branch/+/- move exactly when an agent touches a tree. Unscoped on+// purpose: the tool may belong to a background tile's session, so every+// on-screen worktree re-probes, not just the primary.$workspaceChangeTick.subscribe(() => scheduleRepoStatusRefresh())// A turn settling is the backstop for changes no tool diff announced (e.g. a@@ -216,8 +404,25 @@ $busy.subscribe(busy => {prevBusy = busy})-// External changes while the window was away (an outside terminal) — refresh on-// refocus, the git-GUI standard.+// Window focus: external changes while we were away (an outside terminal).if (typeof window !== 'undefined') {window.addEventListener('focus', () => scheduleRepoStatusRefresh())}++/** Test-only: drop in-flight / pending / registered state so cases don't leak. */+export function _resetCodingStatusForTests(): void {+ if (repoStatusRefreshTimer) {+ clearTimeout(repoStatusRefreshTimer)+ repoStatusRefreshTimer = null+ }++ scheduledCwds.clear()+ scheduledAllTargets = false+ pendingByCwd.clear()+ seqByCwd.clear()+ registeredCwds.clear()+ repoStatusRefreshInFlight = null+ $repoStatusByCwd.set({})+ $repoWorktreesByCwd.set({})+ $repoStatusLoading.set(false)+}diff --git a/apps/desktop/src/store/review.test.ts b/apps/desktop/src/store/review.test.tsindex 6fa68417359..050981d9d04 100644--- a/apps/desktop/src/store/review.test.ts+++ b/apps/desktop/src/store/review.test.ts@@ -13,6 +13,7 @@ import {$reviewMaxChurn,$reviewOpen,$reviewRevertTarget,+ $reviewScopeCwd,$reviewSelectedPath,$reviewShipBusy,$reviewShipInfo,@@ -92,6 +93,7 @@ beforeEach(() => {$reviewShipBusy.set(false)$reviewCommitMsgBusy.set(false)$reviewRevertTarget.set(undefined)+ $reviewScopeCwd.set(null)$currentCwd.set('/repo')})@@ -239,24 +241,57 @@ describe('view state', () => {const review = stubReview()openReview()expect($reviewOpen.get()).toBe(true)+ expect($reviewScopeCwd.get()).toBeNull()// openReview fires refreshReview + refreshShipInfo without awaiting.await Promise.resolve()await Promise.resolve()- expect(review.list).toHaveBeenCalled()+ expect(review.list).toHaveBeenCalledWith('/repo', 'uncommitted', null)})- it('closeReview closes the pane and clears the selection', () => {+ it('openReview pins the pane to a tile worktree when scoped', async () => {+ const review = stubReview({+ list: vi.fn(async () => ({ files: [file('tile.ts')] }))+ })+ openReview('/tile-worktree')+ expect($reviewOpen.get()).toBe(true)+ expect($reviewScopeCwd.get()).toBe('/tile-worktree')+ await Promise.resolve()+ await Promise.resolve()+ expect(review.list).toHaveBeenCalledWith('/tile-worktree', 'uncommitted', null)+ })++ it('closeReview closes the pane, clears selection, and drops scope', () => {stubReview()$reviewOpen.set(true)+ $reviewScopeCwd.set('/tile-worktree')$reviewSelectedPath.set('a.ts')$reviewDiff.set('x')closeReview()expect($reviewOpen.get()).toBe(false)+ expect($reviewScopeCwd.get()).toBeNull()expect($reviewSelectedPath.get()).toBeNull()expect($reviewDiff.get()).toBeNull()})++ it('scoped pane ignores main-pane cwd changes', async () => {+ const review = stubReview({+ list: vi.fn(async (cwd: string) => ({ files: [file(cwd === '/tile' ? 'tile.ts' : 'main.ts')] }))+ })+ openReview('/tile')+ await Promise.resolve()+ await Promise.resolve()+ review.list.mockClear()++ // Main session hops repos; the pane is still pinned to the tile.+ $currentCwd.set('/somewhere-else')+ await Promise.resolve()+ await Promise.resolve()++ expect($reviewScopeCwd.get()).toBe('/tile')+ expect(review.list).not.toHaveBeenCalled()+ })})describe('mutations', () => {diff --git a/apps/desktop/src/store/review.ts b/apps/desktop/src/store/review.tsindex df1f2696d82..91474682f86 100644--- a/apps/desktop/src/store/review.ts+++ b/apps/desktop/src/store/review.ts@@ -84,7 +84,17 @@ export const $reviewShipBusy = atom(false)// True while a commit message is being generated (drives the input's spinner).export const $reviewCommitMsgBusy = atom(false)-const repoCwd = (): null | string => $currentCwd.get()?.trim() || null+// The pane's repo scope. Null = follow the ACTIVE session's cwd (the classic+// behavior). A tile's rail opens the pane pinned to ITS worktree instead —+// tiles can sit in different worktrees than main, and reviewing "the diff I'm+// looking at" must mean that tile's repo, not whatever main happens to be on.+export const $reviewScopeCwd = atom<null | string>(null)++/** The repo the pane is reading right now: its pinned scope, else the active+ * session's cwd. Exported for pane helpers that join repo-relative paths. */+export const reviewRepoCwd = (): null | string => $reviewScopeCwd.get()?.trim() || $currentCwd.get()?.trim() || null++const repoCwd = reviewRepoCwdtype ReviewBridge = NonNullable<NonNullable<NonNullable<Window['hermesDesktop']>['git']>['review']>let reviewRefreshSeq = 0@@ -246,7 +256,10 @@ function refreshShipInfoIfStale(): void {}}-export function openReview(): void {+/** Open the pane scoped to `scopeCwd` (a tile's worktree), or to the active+ * session's cwd when null — see `$reviewScopeCwd`. */+export function openReview(scopeCwd: null | string = null): void {+ $reviewScopeCwd.set(scopeCwd?.trim() || null)$reviewOpen.set(true)void refreshReview()void refreshShipInfo()@@ -254,16 +267,17 @@ export function openReview(): void {export function closeReview(): void {$reviewOpen.set(false)+ $reviewScopeCwd.set(null)clearReviewSelection()}-export function toggleReview(): void {+export function toggleReview(scopeCwd: null | string = null): void {// Narrow width: the pane is a collapsed overlay (like the sidebar under ⌘B).// Make sure its data is loaded, then slide it in/out via the forced-reveal pin// — never the docked open state, which a 0px track would render invisibly.if (matchesQuery(SIDEBAR_COLLAPSE_MEDIA_QUERY)) {if (!$reviewOpen.get()) {- openReview()+ openReview(scopeCwd)}window.dispatchEvent(new CustomEvent(PANE_TOGGLE_REVEAL_EVENT, { detail: { id: REVIEW_PANE_ID } }))@@ -274,7 +288,7 @@ export function toggleReview(): void {if ($reviewOpen.get()) {closeReview()} else {- revealReview()+ revealReview(scopeCwd)}}@@ -283,11 +297,15 @@ export function toggleReview(): void {* closes an already-open pane — it's the "take me to the diff" entry point used* by the transcript's changed-files card.*/-export function revealReview(): void {+export function revealReview(scopeCwd: null | string = null): void {const wasOpen = $reviewOpen.get()if (!wasOpen) {- openReview()+ openReview(scopeCwd)+ } else if (($reviewScopeCwd.get() ?? null) !== (scopeCwd?.trim() || null)) {+ // Already open but on another worktree's diff — re-home it. The scope+ // subscription below clears the stale list and re-probes.+ $reviewScopeCwd.set(scopeCwd?.trim() || null)}if (matchesQuery(SIDEBAR_COLLAPSE_MEDIA_QUERY)) {@@ -322,8 +340,8 @@ function matchReviewFile(files: readonly HermesReviewFile[], path: string): Herm* Open the review pane on one file's diff. The path comes from a tool call, so* it may be absolute while git reports repo-relative — match on the tail.*/-export async function openReviewForPath(path: string): Promise<void> {- revealReview()+export async function openReviewForPath(path: string, scopeCwd: null | string = null): Promise<void> {+ revealReview(scopeCwd)await refreshReview()const file = matchReviewFile($reviewFiles.get(), path)@@ -339,7 +357,7 @@ export async function openReviewForPath(path: string): Promise<void> {// working tree changed). A failure is swallowed by the caller's notify wrapper.async function afterMutation(): Promise<void> {await refreshReview()- void refreshRepoStatus()+ void refreshRepoStatus(repoCwd())const selected = $reviewSelectedPath.get()const file = selected ? $reviewFiles.get().find(f => f.path === selected) : null@@ -414,7 +432,7 @@ export async function commitChanges(message: string, opts: { push?: boolean } =await runShip(async () => {await ctx.review.commit(ctx.cwd, message.trim(), Boolean(opts.push))await refreshReview()- void refreshRepoStatus()+ void refreshRepoStatus(repoCwd())void refreshShipInfo()})}@@ -531,10 +549,14 @@ $busy.subscribe(busy => {prevBusy = busy})-// The active session's cwd changed → the repo changed under the pane. Clear the-// stale file list + selection up front so the pane drops straight to its loading-// skeleton instead of blipping the previous repo's diff into the new one.-$currentCwd.subscribe(() => {+// The pane's repo moved under it. For the classic (unscoped) pane that's the+// active session's cwd changing; for a scoped pane it's a re-home to another+// tile's worktree — and a main-pane cwd change is deliberately IGNORED while+// scoped, so switching sessions in main can't yank the diff you're reviewing.+// Either way: clear the stale file list + selection up front so the pane drops+// straight to its loading skeleton instead of blipping the previous repo's+// diff into the new one.+function onReviewRepoMoved(): void {if ($reviewOpen.get()) {clearReviewSelection()$reviewFiles.set([])@@ -542,6 +564,21 @@ $currentCwd.subscribe(() => {scheduleReviewRefresh()void refreshShipInfo()}+}++$currentCwd.subscribe(() => {+ if (!$reviewScopeCwd.get()) {+ onReviewRepoMoved()+ }+})++let prevScopeCwd = $reviewScopeCwd.get()++$reviewScopeCwd.subscribe(scope => {+ if (scope !== prevScopeCwd) {+ prevScopeCwd = scope+ onReviewRepoMoved()+ }})// An outside terminal may have changed the tree while we were away.