Cache worktree roots for filesystem auth and UI improvements (#306)

* clean-up-repo-local-setup-script

- Add authorization cache for worktree roots to improve filesystem read performance
- Use ensureAuthorizedRootsCache instead of rebuilding on every list operation
- Fix useMemo side effect in WorktreeList by returning sorted IDs directly
- Add error display in QuickOpen and FileExplorer for unauthorized paths
- Improve section order in SourceControl (unstaged, staged, untracked)
- Add keyboard shortcut guard in WorktreeList for arrow keys
- Address review findings from code quality checks

* fix: update test mocks for filesystem-auth cache integration

- filesystem.test.ts: invalidate auth roots cache in beforeEach to
  prevent stale cache state from leaking between tests
- worktrees.test.ts / worktrees-windows.test.ts: add store.getRepos
  mock return value so rebuildAuthorizedRootsCache can iterate repos
- worktrees-windows.test.ts: add third listWorktrees mock for the
  cache rebuild call consumed during worktrees:create

* fix: resolve oxlint errors for max-lines and missing useEffect dependency

- Extract repeated worktree mock data into shared variable to reduce
  worktrees.test.ts below the 300-line limit
- Add missing 'toggleSidebar' to useEffect dependency array in App.tsx
This commit is contained in:
Jinjing
2026-04-05 11:19:15 -07:00
committed by GitHub
parent 399af41312
commit 8a8826b2d6
14 changed files with 257 additions and 87 deletions
+79 -15
View File
@@ -7,11 +7,18 @@ export const PATH_ACCESS_DENIED_MESSAGE =
'Access denied: path resolves outside allowed directories. If this blocks a legitimate workflow, please file a GitHub issue.'
const authorizedExternalPaths = new Set<string>()
const registeredWorktreeRoots = new Set<string>()
let registeredWorktreeRootsDirty = true
let registeredWorktreeRootsRefresh: Promise<void> | null = null
export function authorizeExternalPath(targetPath: string): void {
authorizedExternalPaths.add(resolve(targetPath))
}
export function invalidateAuthorizedRootsCache(): void {
registeredWorktreeRootsDirty = true
}
/**
* Check whether resolvedTarget is equal to or a descendant of resolvedBase.
* Uses relative() so it works with both `/` (Unix) and `\` (Windows) separators.
@@ -46,9 +53,53 @@ export function isPathAllowed(targetPath: string, store: Store): boolean {
if (authorizedExternalPaths.has(resolvedTarget)) {
return true
}
for (const authorizedPath of authorizedExternalPaths) {
if (isDescendantOrEqual(resolvedTarget, authorizedPath)) {
return true
}
}
return getAllowedRoots(store).some((root) => isDescendantOrEqual(resolvedTarget, root))
}
export async function rebuildAuthorizedRootsCache(store: Store): Promise<void> {
const nextRoots = new Set<string>()
for (const repo of store.getRepos()) {
try {
nextRoots.add(await normalizeExistingPath(repo.path))
const worktrees = await listWorktrees(repo.path)
for (const worktree of worktrees) {
nextRoots.add(await normalizeExistingPath(worktree.path))
}
} catch (error) {
// Why: a single inaccessible repo (EACCES, EIO, etc.) must not break
// the entire cache rebuild — that would disable File Explorer and
// Quick Open for all other repos. We skip the failing repo and let
// the rest proceed.
console.warn(`[filesystem-auth] skipping repo ${repo.path} during cache rebuild:`, error)
}
}
registeredWorktreeRoots.clear()
for (const root of nextRoots) {
registeredWorktreeRoots.add(root)
}
registeredWorktreeRootsDirty = false
}
export async function ensureAuthorizedRootsCache(store: Store): Promise<void> {
if (!registeredWorktreeRootsDirty) {
return
}
if (!registeredWorktreeRootsRefresh) {
registeredWorktreeRootsRefresh = rebuildAuthorizedRootsCache(store).finally(() => {
registeredWorktreeRootsRefresh = null
})
}
await registeredWorktreeRootsRefresh
}
/**
* Returns true if the error is an ENOENT (file-not-found) error.
*/
@@ -60,13 +111,13 @@ export function isENOENT(error: unknown): boolean {
export async function resolveAuthorizedPath(targetPath: string, store: Store): Promise<string> {
const resolvedTarget = resolve(targetPath)
if (!isPathAllowed(resolvedTarget, store)) {
if (!(await isPathAllowedIncludingRegisteredWorktrees(resolvedTarget, store))) {
throw new Error(PATH_ACCESS_DENIED_MESSAGE)
}
try {
const realTarget = await realpath(resolvedTarget)
if (!isPathAllowed(realTarget, store)) {
if (!(await isPathAllowedIncludingRegisteredWorktrees(realTarget, store))) {
throw new Error(PATH_ACCESS_DENIED_MESSAGE)
}
return realTarget
@@ -77,13 +128,35 @@ export async function resolveAuthorizedPath(targetPath: string, store: Store): P
const realParent = await realpath(dirname(resolvedTarget))
const candidateTarget = resolve(realParent, basename(resolvedTarget))
if (!isPathAllowed(candidateTarget, store)) {
if (!(await isPathAllowedIncludingRegisteredWorktrees(candidateTarget, store))) {
throw new Error(PATH_ACCESS_DENIED_MESSAGE)
}
return candidateTarget
}
}
async function isPathAllowedIncludingRegisteredWorktrees(
targetPath: string,
store: Store
): Promise<boolean> {
if (isPathAllowed(targetPath, store)) {
return true
}
await ensureAuthorizedRootsCache(store)
// Why: external linked worktrees are already trusted for git operations.
// Cache their normalized roots once and reuse that index so quick-open and
// file explorer do not spawn `git worktree list` on every filesystem read.
for (const root of registeredWorktreeRoots) {
if (isDescendantOrEqual(targetPath, root)) {
return true
}
}
return false
}
async function normalizeExistingPath(targetPath: string): Promise<string> {
try {
return await realpath(targetPath)
@@ -119,20 +192,11 @@ export async function resolveRegisteredWorktreePath(
// symlinks).
const normalizedTarget = await normalizeExistingPath(resolvedTarget)
for (const repo of store.getRepos()) {
const normalizedRepoPath = await normalizeExistingPath(repo.path)
if (normalizedTarget === normalizedRepoPath) {
await ensureAuthorizedRootsCache(store)
for (const root of registeredWorktreeRoots) {
if (normalizedTarget === root) {
return normalizedTarget
}
const worktrees = await listWorktrees(repo.path)
for (const worktree of worktrees) {
const normalizedWorktreePath = await normalizeExistingPath(worktree.path)
if (normalizedTarget === normalizedWorktreePath) {
return normalizedTarget
}
}
}
throw new Error('Access denied: unknown repository or worktree path')
+5
View File
@@ -70,6 +70,7 @@ vi.mock('../git/worktree', () => ({
}))
import { registerFilesystemHandlers } from './filesystem'
import { invalidateAuthorizedRootsCache } from './filesystem-auth'
describe('registerFilesystemHandlers', () => {
const store = {
@@ -114,6 +115,10 @@ describe('registerFilesystemHandlers', () => {
handlers.set(channel, handler)
})
// Reset module-level auth cache so each test starts with a fresh dirty
// flag — prevents stale worktree data from a prior test's cache rebuild.
invalidateAuthorizedRootsCache()
realpathMock.mockImplementation(async (targetPath: string) => targetPath)
listWorktreesMock.mockResolvedValue([
{
+3 -1
View File
@@ -32,7 +32,8 @@ import {
resolveRegisteredWorktreePath,
validateGitRelativeFilePath,
isENOENT,
authorizeExternalPath
authorizeExternalPath,
rebuildAuthorizedRootsCache
} from './filesystem-auth'
import { listQuickOpenFiles } from './filesystem-list-files'
import { registerFilesystemMutationHandlers } from './filesystem-mutations'
@@ -73,6 +74,7 @@ function isBinaryBuffer(buffer: Buffer): boolean {
}
export function registerFilesystemHandlers(store: Store): void {
void rebuildAuthorizedRootsCache(store)
const activeTextSearches = new Map<string, ChildProcessByStdio<null, Readable, Readable>>()
// ─── Filesystem ─────────────────────────────────────────
+4 -1
View File
@@ -4,6 +4,7 @@ import { randomUUID } from 'crypto'
import type { Store } from '../persistence'
import type { Repo } from '../../shared/types'
import { REPO_COLORS } from '../../shared/constants'
import { rebuildAuthorizedRootsCache } from './filesystem-auth'
import {
isGitRepo,
getGitUsername,
@@ -48,12 +49,14 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v
}
store.addRepo(repo)
await rebuildAuthorizedRootsCache(store)
notifyReposChanged(mainWindow)
return repo
})
ipcMain.handle('repos:remove', (_event, args: { repoId: string }) => {
ipcMain.handle('repos:remove', async (_event, args: { repoId: string }) => {
store.removeRepo(args.repoId)
await rebuildAuthorizedRootsCache(store)
notifyReposChanged(mainWindow)
})
+22 -18
View File
@@ -134,6 +134,15 @@ describe('registerWorktreeHandlers – Windows path handling', () => {
handlers[channel] = handler
})
store.getRepos.mockReturnValue([
{
id: 'repo-1',
path: 'C:\\repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0
}
])
store.getRepo.mockReturnValue({
id: 'repo-1',
path: 'C:\\repo',
@@ -200,25 +209,20 @@ describe('registerWorktreeHandlers – Windows path handling', () => {
})
it('preserves create-time metadata on the next list when Windows path formatting differs', async () => {
const worktreeEntry = {
path: 'C:/workspaces/improve-dashboard',
head: 'abc123',
branch: 'refs/heads/improve-dashboard',
isBare: false,
isMainWorktree: false
}
// Three calls: (1) worktrees:create finds the new worktree,
// (2) rebuildAuthorizedRootsCache enumerates worktrees for the repo,
// (3) worktrees:list enumerates worktrees again.
listWorktreesMock
.mockResolvedValueOnce([
{
path: 'C:/workspaces/improve-dashboard',
head: 'abc123',
branch: 'refs/heads/improve-dashboard',
isBare: false,
isMainWorktree: false
}
])
.mockResolvedValueOnce([
{
path: 'C:/workspaces/improve-dashboard',
head: 'abc123',
branch: 'refs/heads/improve-dashboard',
isBare: false,
isMainWorktree: false
}
])
.mockResolvedValueOnce([worktreeEntry])
.mockResolvedValueOnce([worktreeEntry])
.mockResolvedValueOnce([worktreeEntry])
store.setWorktreeMeta.mockReturnValue({
lastActivityAt: 123,
displayName: 'Improve Dashboard'
+45 -46
View File
@@ -101,30 +101,34 @@ describe('registerWorktreeHandlers', () => {
}
beforeEach(() => {
handleMock.mockReset()
removeHandlerMock.mockReset()
listWorktreesMock.mockReset()
addWorktreeMock.mockReset()
removeWorktreeMock.mockReset()
getGitUsernameMock.mockReset()
getDefaultBaseRefMock.mockReset()
getBranchConflictKindMock.mockReset()
getPRForBranchMock.mockReset()
getEffectiveHooksMock.mockReset()
createSetupRunnerScriptMock.mockReset()
shouldRunSetupForCreateMock.mockReset()
runHookMock.mockReset()
hasHooksFileMock.mockReset()
loadHooksMock.mockReset()
computeWorktreePathMock.mockReset()
ensurePathWithinWorkspaceMock.mockReset()
mainWindow.webContents.send.mockReset()
store.getRepos.mockReset()
store.getRepo.mockReset()
store.getSettings.mockReset()
store.getWorktreeMeta.mockReset()
store.setWorktreeMeta.mockReset()
store.removeWorktreeMeta.mockReset()
for (const m of [
handleMock,
removeHandlerMock,
listWorktreesMock,
addWorktreeMock,
removeWorktreeMock,
getGitUsernameMock,
getDefaultBaseRefMock,
getBranchConflictKindMock,
getPRForBranchMock,
getEffectiveHooksMock,
createSetupRunnerScriptMock,
shouldRunSetupForCreateMock,
runHookMock,
hasHooksFileMock,
loadHooksMock,
computeWorktreePathMock,
ensurePathWithinWorkspaceMock,
mainWindow.webContents.send,
store.getRepos,
store.getRepo,
store.getSettings,
store.getWorktreeMeta,
store.setWorktreeMeta,
store.removeWorktreeMeta
]) {
m.mockReset()
}
for (const key of Object.keys(handlers)) {
delete handlers[key]
@@ -134,14 +138,15 @@ describe('registerWorktreeHandlers', () => {
handlers[channel] = handler
})
store.getRepo.mockReturnValue({
const repo = {
id: 'repo-1',
path: '/workspace/repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
worktreeBaseRef: null
})
addedAt: 0
}
store.getRepos.mockReturnValue([repo])
store.getRepo.mockReturnValue({ ...repo, worktreeBaseRef: null })
store.getSettings.mockReturnValue({
branchPrefix: 'none',
nestWorkspaces: false,
@@ -224,16 +229,18 @@ describe('registerWorktreeHandlers', () => {
expect(addWorktreeMock).not.toHaveBeenCalled()
})
const createdWorktreeList = [
{
path: '/workspace/improve-dashboard',
head: 'abc123',
branch: 'improve-dashboard',
isBare: false,
isMainWorktree: false
}
]
it('returns a setup launch payload when setup should run', async () => {
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/improve-dashboard',
head: 'abc123',
branch: 'improve-dashboard',
isBare: false,
isMainWorktree: false
}
])
listWorktreesMock.mockResolvedValue(createdWorktreeList)
getEffectiveHooksMock.mockReturnValue({
scripts: {
setup: 'pnpm worktree:setup'
@@ -269,15 +276,7 @@ describe('registerWorktreeHandlers', () => {
})
it('still returns the created worktree when setup runner generation fails', async () => {
listWorktreesMock.mockResolvedValue([
{
path: '/workspace/improve-dashboard',
head: 'abc123',
branch: 'improve-dashboard',
isBare: false,
isMainWorktree: false
}
])
listWorktreesMock.mockResolvedValue(createdWorktreeList)
getEffectiveHooksMock.mockReturnValue({
scripts: {
setup: 'pnpm worktree:setup'
+12
View File
@@ -32,6 +32,7 @@ import {
formatWorktreeRemovalError,
isOrphanedWorktreeError
} from './worktree-logic'
import { rebuildAuthorizedRootsCache, ensureAuthorizedRootsCache } from './filesystem-auth'
export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store): void {
// Remove any previously registered handlers so we can re-register them
@@ -44,6 +45,10 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
ipcMain.removeHandler('hooks:check')
ipcMain.handle('worktrees:listAll', async () => {
// Why: use ensureAuthorizedRootsCache (not rebuild) to avoid redundantly
// listing git worktrees when the cache is already fresh — the handler
// itself calls listWorktrees for every repo below.
await ensureAuthorizedRootsCache(store)
const repos = store.getRepos()
const allWorktrees: Worktree[] = []
@@ -60,6 +65,10 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
})
ipcMain.handle('worktrees:list', async (_event, args: { repoId: string }) => {
// Why: use ensureAuthorizedRootsCache (not rebuild) to avoid redundantly
// listing git worktrees when the cache is already fresh — the handler
// itself calls listWorktrees below.
await ensureAuthorizedRootsCache(store)
const repo = store.getRepo(args.repoId)
if (!repo) {
return []
@@ -160,6 +169,7 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
}
const meta = store.setWorktreeMeta(worktreeId, metaUpdates)
const worktree = mergeWorktree(repo.id, created, meta)
await rebuildAuthorizedRootsCache(store)
let setup: CreateWorktreeResult['setup']
if (setupScript && shouldLaunchSetup) {
@@ -213,12 +223,14 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
console.warn(`[worktrees] Orphaned worktree detected at ${worktreePath}, cleaning up`)
await rm(worktreePath, { recursive: true, force: true }).catch(() => {})
store.removeWorktreeMeta(args.worktreeId)
await rebuildAuthorizedRootsCache(store)
notifyWorktreesChanged(mainWindow, repoId)
return
}
throw new Error(formatWorktreeRemovalError(error, worktreePath, args.force ?? false))
}
store.removeWorktreeMeta(args.worktreeId)
await rebuildAuthorizedRootsCache(store)
notifyWorktreesChanged(mainWindow, repoId)
}
+1
View File
@@ -381,6 +381,7 @@ function App(): React.JSX.Element {
activeWorktreeId,
openModal,
repos.length,
toggleSidebar,
setRightSidebarTab,
setRightSidebarOpen,
setQuickOpenVisible
+11 -1
View File
@@ -55,6 +55,7 @@ export default function QuickOpen(): React.JSX.Element | null {
const [files, setFiles] = useState<string[]>([])
const [selectedIndex, setSelectedIndex] = useState(0)
const [loading, setLoading] = useState(false)
const [loadError, setLoadError] = useState<string | null>(null)
const inputRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLDivElement>(null)
@@ -88,6 +89,7 @@ export default function QuickOpen(): React.JSX.Element | null {
setQuery('')
setSelectedIndex(0)
setFiles([])
setLoadError(null)
setLoading(true)
void window.api.fs
@@ -97,9 +99,12 @@ export default function QuickOpen(): React.JSX.Element | null {
setFiles(result)
}
})
.catch(() => {
.catch((error) => {
if (!cancelled) {
setFiles([])
// Why: treating list-files failures as "no matches" hides the real
// cause when the active worktree path is unauthorized or stale.
setLoadError(error instanceof Error ? error.message : String(error))
}
})
.finally(() => {
@@ -232,6 +237,11 @@ export default function QuickOpen(): React.JSX.Element | null {
Loading files...
</div>
)}
{!loading && loadError && (
<div className="px-3 py-6 text-center text-xs text-muted-foreground">
Could not load files: {loadError}
</div>
)}
{filtered.length === 0 && query.trim() && (
<div className="px-3 py-6 text-center text-xs text-muted-foreground">
No matching files
@@ -19,7 +19,13 @@ function computeLineStats(
original: string,
modified: string,
status: string
): { added: number; removed: number } {
): { added: number; removed: number } | null {
// Why: for very large files (e.g. package-lock.json), splitting and
// iterating synchronously in the React render cycle would block the
// main thread and freeze the UI. Return null to skip stats display.
if (original.length + modified.length > 500_000) {
return null
}
if (status === 'added') {
return { added: modified ? modified.split('\n').length : 0, removed: 0 }
}
@@ -47,6 +47,7 @@ export default function FileExplorer(): React.JSX.Element {
flatRows,
rowsByPath,
rootCache,
rootError,
loadDir,
refreshTree,
refreshDir,
@@ -267,6 +268,13 @@ export default function FileExplorer(): React.JSX.Element {
</div>
)
}
if (rootError) {
return (
<div className="flex h-full items-center justify-center px-4 text-center text-[11px] text-muted-foreground">
Could not load files for this worktree: {rootError}
</div>
)
}
return (
<div className="flex h-full items-center justify-center text-[11px] text-muted-foreground px-4 text-center">
No files in this worktree
@@ -71,7 +71,7 @@ const STATUS_ICONS: Record<
// are assigned area:'unstaged' by the parser — appear above "Staged Changes".
// This keeps unresolved conflicts visible at the top of the list where the
// user won't miss them.
const SECTION_ORDER = ['untracked', 'unstaged', 'staged'] as const
const SECTION_ORDER = ['unstaged', 'staged', 'untracked'] as const
const SECTION_LABELS: Record<(typeof SECTION_ORDER)[number], string> = {
staged: 'Staged Changes',
unstaged: 'Changes',
@@ -9,6 +9,7 @@ type UseFileExplorerTreeResult = {
flatRows: TreeNode[]
rowsByPath: Map<string, TreeNode>
rootCache: DirCache | undefined
rootError: string | null
loadDir: (dirPath: string, depth: number, options?: { force?: boolean }) => Promise<void>
refreshTree: () => Promise<void>
refreshDir: (dirPath: string) => Promise<void>
@@ -20,6 +21,7 @@ export function useFileExplorerTree(
expanded: Set<string>
): UseFileExplorerTreeResult {
const [dirCache, setDirCache] = useState<Record<string, DirCache>>({})
const [rootError, setRootError] = useState<string | null>(null)
const dirCacheRef = useRef(dirCache)
dirCacheRef.current = dirCache
@@ -38,6 +40,9 @@ export function useFileExplorerTree(
}))
try {
const entries = await window.api.fs.readDir({ dirPath })
if (depth === -1) {
setRootError(null)
}
const children: TreeNode[] = entries
.filter(shouldIncludeFileExplorerEntry)
.map((entry) => ({
@@ -50,7 +55,14 @@ export function useFileExplorerTree(
depth: depth + 1
}))
setDirCache((prev) => ({ ...prev, [dirPath]: { children, loading: false } }))
} catch {
} catch (error) {
if (depth === -1) {
// Why: the old implementation collapsed root read failures into an
// empty tree, which made authorization/path bugs look like a real
// empty worktree. Preserve the message so the UI can distinguish
// "no files" from "could not read this worktree".
setRootError(error instanceof Error ? error.message : String(error))
}
setDirCache((prev) => ({ ...prev, [dirPath]: { children: [], loading: false } }))
}
},
@@ -111,6 +123,7 @@ export function useFileExplorerTree(
const resetAndLoad = useCallback(() => {
setDirCache({})
setRootError(null)
if (worktreePath) {
void loadDir(worktreePath, -1, { force: true })
}
@@ -121,6 +134,7 @@ export function useFileExplorerTree(
flatRows,
rowsByPath,
rootCache,
rootError,
loadDir,
refreshTree,
refreshDir,
@@ -36,6 +36,7 @@ const WorktreeList = React.memo(function WorktreeList() {
groupBy === 'pr-status' || sortBy === 'recent' ? s.prCache : null
)
const sortEpoch = useAppStore((s) => s.sortEpoch)
const scrollRef = useRef<HTMLDivElement>(null)
const repoMap = useMemo(() => {
@@ -46,7 +47,32 @@ const WorktreeList = React.memo(function WorktreeList() {
return m
}, [repos])
// Flatten and filter the current live worktree data first.
// ── Stable sort order ──────────────────────────────────────────
// The sort order is cached and only recomputed when `sortEpoch` changes
// (worktree add/remove, terminal activity, backend refresh, etc.).
// Selection-triggered side-effects (clearing isUnread, GitHub refresh)
// do NOT bump sortEpoch, so clicking a card never reorders the list.
//
// Why useMemo instead of useEffect: the sort order must be computed
// synchronously *before* the worktrees memo reads it, otherwise the
// first render (and epoch bumps) would use stale/empty data from the ref.
const sortedIds = useMemo(() => {
const state = useAppStore.getState()
const allWorktrees: Worktree[] = Object.values(state.worktreesByRepo)
.flat()
.filter((w) => !w.isArchived)
const currentRepoMap = new Map(state.repos.map((r) => [r.id, r]))
const currentTabs = state.tabsByWorktree
allWorktrees.sort(
buildWorktreeComparator(sortBy, currentTabs, currentRepoMap, state.prCache, Date.now())
)
return allWorktrees.map((w) => w.id)
// sortEpoch is an intentional trigger: it's not read inside the memo, but
// its change signals that the sort order should be recomputed.
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [sortEpoch, sortBy, prCache])
// Flatten, filter, and apply stable sort order
const visibleWorktrees = useMemo(() => {
let all: Worktree[] = Object.values(worktreesByRepo).flat()
@@ -78,8 +104,18 @@ const WorktreeList = React.memo(function WorktreeList() {
})
}
// Apply cached sort order. Items not yet in the cache (e.g. brand-new
// worktrees before the next sortEpoch bump) are appended at the end.
const orderIndex = new Map(sortedIds.map((id, i) => [id, i]))
all.sort((a, b) => {
const ai = orderIndex.get(a.id) ?? Infinity
const bi = orderIndex.get(b.id) ?? Infinity
return ai - bi
})
return all
}, [worktreesByRepo, filterRepoIds, searchQuery, showActiveOnly, repoMap, tabsByWorktree])
}, [worktreesByRepo, filterRepoIds, searchQuery, showActiveOnly, repoMap, tabsByWorktree, sortedIds])
const latestRecentSortInputsRef = useRef<Record<string, RecentSortOverride>>({})
const frozenActiveRecentSortRef = useRef<{
@@ -275,6 +311,12 @@ const WorktreeList = React.memo(function WorktreeList() {
const handleContainerKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
// Why: only capture bare arrow keys when the list container itself is
// focused. If focus is on an inner input or button, arrow keys should
// perform their native function (e.g. cursor movement in text fields).
if (e.target !== e.currentTarget) {
return
}
navigateWorktree(e.key === 'ArrowUp' ? 'up' : 'down')
e.preventDefault()
} else if (e.key === 'Enter') {